You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm sure this has been talked about before, but I can't find a clear issue for it. I'm playing around with using webpack with server-side node modules (using target: node). I started to like the idea of bundling of everything into a single js file because that would be cool for deployment, but what kills that idea is binary dependencies. They definitely can't be bundled in, though you might know of a hack that lets me alias them or something.
Is there any way to tell the system ignore bundling anything coming from node_modules, and just leave it as a require statement?
I don't know if the IgnorePlugin means that, but if so, trying it results in an error: plugins: [ new webpack.IgnorePlugin(/.*/, /.*node_modules.*/) ]
% webpack --config webpack.node.config.js
/Users/james/projects/jlongster4/node_modules/webpack/lib/Compilation.js:203
factory.create(module.context, dependencies[0], function(err, dependantModul
^
TypeError: Cannot read property 'context' of null
at Tapable.<anonymous> (/Users/james/projects/jlongster4/node_modules/webpack/lib/Compilation.js:203:24)
That code actually doesn't work. It doesn't take any aliases into account. I only have one alias, but I really don't want to have to duplicate all the aliases in the regexp.
Is there any way to run webpack's resolution algorithm and be able to test on the resulting path?
Have you tried node-loader? I've never used it, but it may fix your native dependencies. Ignoring node_modules in its entirety kind of defeats the purpose of webpack, doesn't it?
Can you give any examples of modules you are trying to require?
There's no way I'm going to load my node modules any differently (having to prepend them with node! or something)
It doesn't defeat the purpose at all; if I get this working, I can entirely get rid of my gulp setup. I get the exact same transformations for my server code as I do with my frontend code and I get the watcher for free that is based on my dependency tree.
what are you actually trying to do? package up identical code for node and the client? ignore some things for the client, but not for the server?
It's not even that complicated: I just have some node code. I want to transform it (6to5, etc). I'm tired of using gulp & webpack and having two systems implement the same transformations. webpack is better in that it is based on my dependency graph, so the watcher automatically knows what to watch, and I'd rather just use it.
@sokra yep, that's basically what I landed on in #839 (comment). thanks. How come I have to specify an external as { foo: 'commonjs foo' }? If I just pass 'foo' it turns this:
It goes hand in hand with the library type (output.libraryTarget).
So when emitting a script module (which is the default) it tries to access the global var foo.
When emitting a CommonJs module (output.libraryTarget = "commonjs2") it requires the module require("foo")
When emitting an AMD module (output.libraryTarget = "amd") it puts the external in the define dependencies define(["foo"], function(...) { ... }).
And when emitting an UMD module it decides depending on environment.
@sokra ah interesting, thanks for the explanation. I actually want to generate a script module (my whole backend code) but I want it to use require("foo")... Ah well, I can do it with a custom function that manually forces the commonjs style. Still trying to figure out if this is worth it. Seems like the node target is supported but nobody really uses it.
This thread is extremely helpful but the proposed solution does not account for submodules. I tried using npm ls --only=production --parseable to compile a flattened list of module names but couldn't figure out how to convert it into a utility method.
The solution that I found, which is a slight derivative of what is in the config docs is this:
config.externals = [
// Every non-relative module is external
// abc -> require("abc")
/^[a-z\/\-0-9]+$/i
];
The key difference between this and the docs is the addition of the i flag and the / character to the regular expression. It has a few holes, like if you have a . legitimately in the path name of the external require, but otherwise works great with things like:
import createMemoryHistory from 'history/lib/createMemoryHistory';
This is all way too confusing for such a common use case: I have a universal ES6 Node app and I want webpack to transpile a server bundle without needlessly including node modules.
Note that the above codes all have a bug when including a module with a "/" in its name to indicate a submodule,
e.g: import ReactDOMServer from "react-dom/server"
This still will cause the entire react-dom package and all its subdependencies to be bundled. I was wondering why my hello world was 800kb, and saw that this import line was breaking it.
The following code can be used to handle this edge case and properly let it be imported by commonjs:
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();
}
}
...
externals: nodeModulesTransform
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
...
};
Reacted by Hao Zhang and Ben Lawson
Reacted by Dariusz Filipiak and aliveAmy
Reacted by Justin Abene, Valentin Cocaud, James and Emery Denuccio
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
...
};
—
Reply to this email directly or view it on GitHub #839 (comment).
I just published webpack-externals-plugin. It has the advantage of supporting external modules that were installed after the initialization of the webpack compiler.
Bit different take but this is my preference. Instead of reading the file system, this just reads the package.json's dependency names and includes them all as externals.
The benefit to this approach is that I only exclude node_modules when compiling webpack libraries, and those dependencies should all be in the package.json for the library being webpack'ed.
I have a few issues with the two popular approaches:
regex to externalize non-relative paths
Almost good but frail when using webpack aliases to common areas in your app (they will look as though they are a node_module when really they should be bundled).
Reading node_modules approach
Scoped modules go in a subdirectory within node_modules, if you try and import '@myscoped/package' the external is only good for '@myscoped' and your scoped modules will be bundled when they shouldn't.
If you haven't npm pruned prior to running webpack and your dependencies have changed there will be extra externals pulled in than should be.
There should be no scenario when you are importing a node_modules package within your library that is not called out in your package.json dependencies, but there will likely be many sibling libraries that get pulled in by NPM that you do not need to externalize.
npm 2 / 3 handle dependencies differently and there will be varying levels of recursion. Seems prone to breakage as library gets larger / more dependencies.
If I am off on anything here please set me straight.
Reacted by Daniel Waddington, Garret LeCompte, Wilson Fung, Ray B and Turadg Aleahmad
@cchamberlain Great suggestion. I updated webpack-node-externals to accept modulesFromFile flag, that will read the modules from the package.json file instead of the node_modules dir:
// webpack.config.jsvarnodeExternals=require('webpack-node-externals');
...
module.exports={
...
externals: [nodeExternals({modulesFromFile: true})],// in order to ignore all modules in package.json when bundling
...
};
Reacted by Daniel Waddington, Cole Chamberlain, Garret LeCompte, Thomas Lent, Valentin Cocaud, James, Pavel Koltyshev, ryuever, Erki Esken, Jonathan Warykowski and 2 more
Activity
troutowicz commentedon Mar 2, 2015
Sounds like you may be looking for externals
http://webpack.github.io/docs/configuration.html#externals
jlongster commentedon Mar 2, 2015
I suppose this works:
I haven't fully tested it though... I'd be surprised if nobody has tried this before?
jlongster commentedon Mar 2, 2015
That code actually doesn't work. It doesn't take any aliases into account. I only have one alias, but I really don't want to have to duplicate all the aliases in the regexp.
Is there any way to run webpack's resolution algorithm and be able to test on the resulting path?
jlongster commentedon Mar 2, 2015
So here's another solution. We could just manually list the modules in
node_modulesand check them explicity:I think this actually works pretty well. I'm still confused how anyone uses webpack with node without running into the binary dependency problem
troutowicz commentedon Mar 2, 2015
Have you tried node-loader? I've never used it, but it may fix your native dependencies. Ignoring node_modules in its entirety kind of defeats the purpose of webpack, doesn't it?
Can you give any examples of modules you are trying to require?
ryanflorence commentedon Mar 2, 2015
what are you actually trying to do? package up identical code for node and the client? ignore some things for the client, but not for the server?
jlongster commentedon Mar 2, 2015
There's no way I'm going to load my node modules any differently (having to prepend them with
node!or something)It doesn't defeat the purpose at all; if I get this working, I can entirely get rid of my gulp setup. I get the exact same transformations for my server code as I do with my frontend code and I get the watcher for free that is based on my dependency tree.
jlongster commentedon Mar 2, 2015
It's not even that complicated: I just have some node code. I want to transform it (6to5, etc). I'm tired of using gulp & webpack and having two systems implement the same transformations. webpack is better in that it is based on my dependency graph, so the watcher automatically knows what to watch, and I'd rather just use it.
sokra commentedon Mar 2, 2015
troutowicz commentedon Mar 2, 2015
You wouldn't have to load your node modules any differently. You would add a loader in your webpack config.
jlongster commentedon Mar 2, 2015
@sokra yep, that's basically what I landed on in #839 (comment). thanks. How come I have to specify an external as { foo: 'commonjs foo' }? If I just pass 'foo' it turns this:
into this:
jlongster commentedon Mar 2, 2015
Yes, you do, you have to now suffix all of them with ".node" which is unacceptable.
troutowicz commentedon Mar 2, 2015
I thought that was the purpose of resolve-extensions
sokra commentedon Mar 2, 2015
It goes hand in hand with the library type (
output.libraryTarget).So when emitting a script module (which is the default) it tries to access the global var
foo.When emitting a CommonJs module (
output.libraryTarget = "commonjs2") itrequires the modulerequire("foo")When emitting an AMD module (
output.libraryTarget = "amd") it puts the external in thedefinedependenciesdefine(["foo"], function(...) { ... }).And when emitting an UMD module it decides depending on environment.
https://github.com/webpack/webpack/tree/master/examples/externals
jlongster commentedon Mar 2, 2015
@sokra ah interesting, thanks for the explanation. I actually want to generate a script module (my whole backend code) but I want it to use
require("foo")... Ah well, I can do it with a custom function that manually forces the commonjs style. Still trying to figure out if this is worth it. Seems like thenodetarget is supported but nobody really uses it.11 remaining items
jachenry commentedon Oct 3, 2015
This thread is extremely helpful but the proposed solution does not account for submodules. I tried using
npm ls --only=production --parseableto compile a flattened list of module names but couldn't figure out how to convert it into a utility method.kpdecker commentedon Oct 26, 2015
The solution that I found, which is a slight derivative of what is in the config docs is this:
The key difference between this and the docs is the addition of the
iflag and the/character to the regular expression. It has a few holes, like if you have a.legitimately in the path name of the external require, but otherwise works great with things like:prashaantt commentedon Jan 15, 2016
FWIW, I was following along @jlongster's excellent series on using Webpack with node, and ran into similar issues with React and others as above. In my experience, the only reliable way is to include all node modules in
externals. I did it this way: https://gist.github.com/prashaantt/257cf2a8cf4e8ee7f847.gimenete commentedon Jan 20, 2016
I've also had the same issue and based on the externals example I did this:
And then use
externals: node_modules.jaydenseric commentedon Jan 21, 2016
This is all way too confusing for such a common use case: I have a universal ES6 Node app and I want webpack to transpile a server bundle without needlessly including node modules.
This is the only thing that has worked:
Then using
externals: nodeModulesin the config.gimenete commentedon Jan 21, 2016
I agree, this is a pretty common use case. There should be a configuration option to do just this.
lingz commentedon Jan 30, 2016
Note that the above codes all have a bug when including a module with a "/" in its name to indicate a submodule,
e.g:
import ReactDOMServer from "react-dom/server"This still will cause the entire react-dom package and all its subdependencies to be bundled. I was wondering why my hello world was 800kb, and saw that this import line was breaking it.
The following code can be used to handle this edge case and properly let it be imported by commonjs:
You can see my complete webpack config with this working here:
https://gist.github.com/lingz/14ad8ea44998f5009d5d
liady commentedon Feb 11, 2016
You can also use webpack-node-externals to achieve this result:
bman654 commentedon Feb 11, 2016
@liady brilliant find.
On Thu, Feb 11, 2016 at 5:29 AM, Liad Yosef [email protected]
wrote:
Brandon Wallace
Palladium Consulting
http://www.palladiumconsulting.com/
alexkirsz commentedon Feb 20, 2016
I just published webpack-externals-plugin. It has the advantage of supporting external modules that were installed after the initialization of the webpack compiler.
danwad commentedon Mar 9, 2016
@Morhaus: webpack-externals-plugin looks like a very neat solution. Going to give it a go. Thanks :)
Set webpack externals to node_modules to resolve binary dependencies
cchamberlain commentedon Apr 26, 2016
Bit different take but this is my preference. Instead of reading the file system, this just reads the package.json's dependency names and includes them all as externals.
The benefit to this approach is that I only exclude node_modules when compiling webpack libraries, and those dependencies should all be in the package.json for the library being webpack'ed.
(I transpile my config with Babel)
I have a few issues with the two popular approaches:
regex to externalize non-relative paths
Reading node_modules approach
npm pruned prior to running webpack and your dependencies have changed there will be extra externals pulled in than should be.If I am off on anything here please set me straight.
liady commentedon Apr 26, 2016
@cchamberlain Great suggestion. I updated webpack-node-externals to accept
modulesFromFileflag, that will read the modules from thepackage.jsonfile instead of thenode_modulesdir:hinell commentedon Jan 29, 2017
Here is my way to prevent node_modules from being bundled:
Output bundle requests then look like this (require isn't declared in result bundle):