Skip to content

Instantly share code, notes, and snippets.

@lingz
Created January 30, 2016 16:01
Show Gist options
  • Save lingz/14ad8ea44998f5009d5d to your computer and use it in GitHub Desktop.
Save lingz/14ad8ea44998f5009d5d to your computer and use it in GitHub Desktop.
Excluding node_modules from webpack build
var Fs = require('fs')
var nodeModules = {}
Fs.readdirSync('node_modules').forEach(function (module) {
if (module !== '.bin') {
nodeModules[module] = true
}
})
var nodeModulesTransform = function(context, request, callback) {
// search for a '/' indicating a nested module
var slashIndex = request.indexOf("/");
var rootModuleName;
if (slashIndex == -1) {
rootModuleName = request;
} else {
rootModuleName = request.substr(0, slashIndex);
}
// Match for root modules that are in our node_modules
if (nodeModules.hasOwnProperty(rootModuleName)) {
callback(null, "commonjs " + request);
} else {
callback();
}
}
module.exports = {
target: 'node',
entry: './src/server.js',
output: {
filename: "./build/server.js"
},
externals: nodeModulesTransform,
module: {
loaders: [
{
loader: 'babel',
test: /\.js$/,
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
devtool: 'source-map'
}
@zohar1000
Copy link

Hi,

Thanks for the code, I tried it and there are couple of issues with it:

  1. There is an error message on the client side saying "require not found", the thing
    is that "webpack-hot-middleware" gets excluded from bundle.js and it should probably be in it.
  2. The function "nodeModulesTransform" determines about inclusion/exclusion of modules based on
    their names, however the module name should be check along with its context since webpack
    checks a dependency tree and the function is invoked for modules which are in different directories then
    the root. This didn't cause a bug on my test app but the code should be changed.

I ended up with a code I saw in one of the threads and it worked fine for me:
fs.readdirSync('node_modules')
.forEach(function(moduleName) {
if (moduleName !== '.bin') nodeModules[moduleName] = 'commonjs ' + moduleName;
});

Thanks,
Zohar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment