I'm learning React and I'm trying to use it with Webpack, but I'm facing the following issue:
If I use this webpack config, the node modules don't get excluded and the bundling process takes 20 second and the bundle's size is over 2MBs (see CLI output below):
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' },
]
}
}
...
However, if I add the following two lines to my config and use nodeExternals the bundle becomes small and runs quickly, although its not working because in the browser I'm getting the error 'Uncaught ReferenceError: require is not defined':
...
target: 'node', // important in order not to bundle built-in modules like path, fs, etc.
externals: [nodeExternals()]
...
What am I missing here? I suppose the browser throws this error, because react doesnt exist on client side anymore after I exclude node_modules, however I suppose the node_modules shouldn't be bundled. Please, find the repo of my small project with the problem here: https://github.com/sznrbrt/messageboard-react
SOLUTION:
Two different ways are either passing an excluding or including option for the loader with a regex of /node_modules/
...
exclude: /(node_modules|bower_components)/,
...
...
{ test: /\.js?$/,
include: [
path.resolve(__dirname, './src'),
],
loader: 'babel-loader?cacheDirectory',
},
...
webpack-node-externals, for example, excludes all modules from the node_modules directory and provides options to allowlist packages.
webpack does not include node_modules dependency!!
The answer is to add exclude: /node_modules/
field inside module.loaders
.
Adding target: 'node' means pack this code to run in node.js environment where node specific global variable is included like require
. This is the reason it does not run in browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With