我正在学习React,我正在尝试将它与Webpack一起使用,但我遇到了以下问题: 如果我使用此webpack配置,则不会排除节点模块,捆绑过程需要20秒,捆绑包的大小超过2MB(请参阅下面的CLI输出):
如果我使用此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)(\?[\s\S]+)?$/,
loader: 'file'
},
// Bootstrap 3
{ test:/bootstrap-sass[\/\\]assets[\/\\]javascripts[\/\\]/, loader: 'imports?jQuery=jquery' },
]
}
}
…
但是,如果我将以下两行添加到我的配置并使用nodeExternals,则捆绑包变小并且运行得很快,虽然它不起作用,因为在浏览器中我收到错误’未捕获的ReferenceError:require未定义’:
... target: 'node', // important in order not to bundle built-in modules like path, fs, etc. externals: [nodeExternals()] ...
我在这里错过了什么?我想浏览器会抛出这个错误,因为在我排除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.这就是它不能在浏览器中运行的原因.
