reactjs - React + Webpack bundling - if node_modules are excluded 'require is not defined' in browser -


i'm learning react , i'm trying use webpack, i'm facing following issue:

if use webpack config, node modules don't excluded , bundling process takes 20 second , bundle's size on 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' },     ]   } } 

cli output 1

... enter image description here

however, if add following 2 lines config , use nodeexternals bundle becomes small , runs quickly, although not working because in browser i'm getting error 'uncaught referenceerror: require not defined':

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

enter image description here

what missing here? suppose browser throws error, because react doesnt exist on client side anymore after exclude node_modules, suppose node_modules shouldn't bundled. please, find repo of small project problem here: https://github.com/sznrbrt/messageboard-react

solution:

two different ways either passing excluding or including option loader regex of /node_modules/

... exclude: /(node_modules|bower_components)/, ...    ...   { test: /\.js?$/,     include: [       path.resolve(__dirname, './src'),     ],     loader: 'babel-loader?cachedirectory',   },   ... 

the answer add exclude: /node_modules/ field inside module.loaders.

adding target: 'node' means pack code run in node.js environment node specific global variable included require. reason not run in browser.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -