加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React Webpack捆绑 – 如果在浏览器中排除了“requir

发布时间:2020-12-15 20:13:26 所属栏目:百科 来源:网络整理
导读:我正在学习React,我正在尝试将它与Webpack一起使用,但我遇到了以下问题: 如果我使用此webpack配置,则不会排除节点模块,捆绑过程需要20秒,捆绑包的大小超过2MB(请参阅下面的CLI输出): const path = require('path');const nodeExternals = require('webpack
我正在学习React,我正在尝试将它与Webpack一起使用,但我遇到了以下问题:

如果我使用此webpack配置,则不会排除节点模块,捆绑过程需要20秒,捆绑包的大小超过2MB(请参阅下面的CLI输出):

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: [
    'bootstrap-loader','./src/index.js','style!css!./src/style/style.css'
  ],output: {
    path: path.resolve(__dirname + 'build'),filename: 'bundle.js'
  },module: {
    loaders: [
      { test: /.jsx?$/,loader: 'babel-loader'
      },{
        test: /.scss$/,loaders: [
          'style','css?modules&importLoaders=2&localIdentName=[name]__[local]__[hash:base64:5]','postcss','sass',],},{
        test: /.woff2?(?v=[0-9].[0-9].[0-9])?$/,loader: "url?limit=10000"
      },{
        test: /.(ttf|eot|svg)(?[sS]+)?$/,loader: 'file'
      },// Bootstrap 3
      { test:/bootstrap-sass[/]assets[/]javascripts[/]/,loader: 'imports?jQuery=jquery' },]
  }
}

CLI output 1


enter image description here

但是,如果我将以下两行添加到我的配置并使用nodeExternals,则捆绑包变小并且运行得很快,虽然它不起作用,因为在浏览器中我收到错误’未捕获的ReferenceError:require未定义’:

...
  target: 'node',// important in order not to bundle built-in modules like path,fs,etc.
  externals: [nodeExternals()]
  ...

enter image description here

我在这里错过了什么?我想浏览器会抛出这个错误,因为在我排除node_modules后,在客户端不再存在反应,但是我想不应该捆绑node_modules.
请在这里找到我的小项目的回购问题:
https://github.com/sznrbrt/messageboard-react

解:

两种不同的方法是使用/ node_modules /的正则表达式为加载器传递排除或包含选项

...
exclude: /(node_modules|bower_components)/,...

  ...
  { test: /.js?$/,include: [
      path.resolve(__dirname,'./src'),loader: 'babel-loader?cacheDirectory',...

解决方法

答案是在module.loaders中添加exclude:/ node_modules / field.

添加目标:’node’表示将此代码打包在node.js环境中运行,其中包含节点特定的全局变量,如require.这就是它不能在浏览器中运行的原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读