chtefi
2/14/2016 - 10:00 PM

Declare all node_modules as externals for Webpack

Declare all node_modules as externals for Webpack

// this way, the whole code won't appear in the bundle, only a single statement (a require, a global var, it depends)

// enhance this code when really using it, it's ugly :-)
var nodeModules = {};
require('fs').readdirSync('node_modules').forEach(function (module) {
  if (module !== '.bin') { nodeModules[module] = 'commonjs ' + module; }
});
...
  externals: nodeModules
...

// that will create a dummy require('xxx') in the bundle itself. (commonjs means to use "require")
// other modes are available (https://webpack.github.io/docs/configuration.html#externals) :

/*
“var”	"abc"	module.exports = abc;
“var”	"abc.def"	module.exports = abc.def;
“this”	"abc"	(function() { module.exports = this["abc"]; }());
“this”	["abc", "def"]	(function() { module.exports = this["abc"]["def"]; }());
“commonjs”	"abc"	module.exports = require("abc");
“commonjs”	["abc", "def"]	module.exports = require("abc").def;
“amd”	"abc"	define(["abc"], function(X) { module.exports = X; })
“umd”	"abc"	everything above
*/