Skip to content

ignoring node_modules #839

Closed
Closed

Description

@jlongster

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)

Activity

  1. jlongster commented on Mar 2, 2015

    @jlongster
    Author

    I suppose this works:

      externals: [
        function(context, request, cb) {
          if(/^[a-z\-0-9]+$/.test(request)) {
            cb(null, 'commonjs ' + request);
            return;
          }
          cb();
        }
      ]

    I haven't fully tested it though... I'd be surprised if nobody has tried this before?

  2. jlongster commented on Mar 2, 2015

    @jlongster
    Author

    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?

  3. jlongster commented on Mar 2, 2015

    @jlongster
    Author

    So here's another solution. We could just manually list the modules in node_modules and check them explicity:

    var node_modules = fs.readdirSync('node_modules').filter(function(x) { return x !== '.bin' });
    
    // ...
    
      externals: function(context, request, cb) {
        if(node_modules.indexOf(request) !== -1) {
          cb(null, 'commonjs ' + request);
          return;
        }
        cb();
      }

    I think this actually works pretty well. I'm still confused how anyone uses webpack with node without running into the binary dependency problem

  4. troutowicz commented on Mar 2, 2015

    @troutowicz

    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?

  5. ryanflorence commented on Mar 2, 2015

    @ryanflorence

    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?

  6. jlongster commented on Mar 2, 2015

    @jlongster
    Author

    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.

  7. jlongster commented on Mar 2, 2015

    @jlongster
    Author

    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.

  8. sokra commented on Mar 2, 2015

    @sokra
    Member
    var node_modules = fs.readdirSync('node_modules').filter(function(x) { return x !== '.bin' });
    
    {
      target: "node",
      externals: node_modules,
      output: {
        libraryTarget: "commonjs2"
      }
    }
  9. troutowicz commented on Mar 2, 2015

    @troutowicz

    You wouldn't have to load your node modules any differently. You would add a loader in your webpack config.

    module.exports = {
      ...
      module: {
        loaders: [
          { test: /\.node$/, loader: 'node-loader' }
        ]
      },
      ...
    };
    
  10. jlongster commented on Mar 2, 2015

    @jlongster
    Author

    @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:

    var foo = require('foo');
    

    into this:

    var foo = foo;
    
  11. jlongster commented on Mar 2, 2015

    @jlongster
    Author

    You wouldn't have to load your node modules any differently. You would add a loader in your webpack config.

    Yes, you do, you have to now suffix all of them with ".node" which is unacceptable.

  12. troutowicz commented on Mar 2, 2015

    @troutowicz

    I thought that was the purpose of resolve-extensions

  13. sokra commented on Mar 2, 2015

    @sokra
    Member

    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.

    https://github.com/webpack/webpack/tree/master/examples/externals

  14. jlongster commented on Mar 2, 2015

    @jlongster
    Author

    @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.

  15. 11 remaining items

  16. jachenry commented on Oct 3, 2015

    @jachenry

    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.

  17. kpdecker commented on Oct 26, 2015

    @kpdecker
    Contributor

    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';
    
  18. prashaantt commented on Jan 15, 2016

    @prashaantt

    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.

  19. gimenete commented on Jan 20, 2016

    @gimenete

    I've also had the same issue and based on the externals example I did this:

    var node_modules = {}
    fs.readdirSync('node_modules').forEach(function(module) {
      node_modules[module] = "require('"+module+"')"
    })

    And then use externals: node_modules.

  20. jaydenseric commented on Jan 21, 2016

    @jaydenseric

    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:

    var Fs = require('fs')
    var nodeModules = {}
    Fs.readdirSync('node_modules').forEach(function (module) {
      if (module !== '.bin') nodeModules[module] = 'commonjs ' + module
    })

    Then using externals: nodeModules in the config.

  21. gimenete commented on Jan 21, 2016

    @gimenete

    I agree, this is a pretty common use case. There should be a configuration option to do just this.

  22. lingz commented on Jan 30, 2016

    @lingz

    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
    

    You can see my complete webpack config with this working here:
    https://gist.github.com/lingz/14ad8ea44998f5009d5d

  23. liady commented on Feb 11, 2016

    @liady

    You can also use webpack-node-externals to achieve this result:

    var nodeExternals = require('webpack-node-externals');
    ...
    module.exports = {
        ...
        externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
        ...
    };
    
  24. bman654 commented on Feb 11, 2016

    @bman654

    @liady brilliant find.

    On Thu, Feb 11, 2016 at 5:29 AM, Liad Yosef [email protected]
    wrote:

    You can also use webpack-node-externals
    https://github.com/liady/webpack-node-externals to achieve this result:

    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).

    Brandon Wallace
    Palladium Consulting
    http://www.palladiumconsulting.com/

  25. alexkirsz commented on Feb 20, 2016

    @alexkirsz

    I just published webpack-externals-plugin. It has the advantage of supporting external modules that were installed after the initialization of the webpack compiler.

      plugins: [
        new ExternalsPlugin({
          type: 'commonjs',
          include: __dirname + '/node_modules',
        }),
      ],
  26. danwad commented on Mar 9, 2016

    @danwad

    @Morhaus: webpack-externals-plugin looks like a very neat solution. Going to give it a go. Thanks :)

  27. cchamberlain commented on Apr 26, 2016

    @cchamberlain

    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)

    import packageJSON from './package.json'
    const { dependencies = {}, devDependencies = {}, peerDependencies = {}, optionalDependencies = {} } = packageJSON
    const dependencyNames = Array.from(new Set( [ ...Object.keys(dependencies)
                                                , ...Object.keys(devDependencies)
                                                , ...Object.keys(peerDependencies)
                                                , ...Object.keys(optionalDependencies)
                                                ] ))
    const externals = dependencyNames.reduce((externals, name) => ({ ...externals, [name]: true }), {})
    export default { externals 
                   , /** rest of config here */
                   }

    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.

  28. liady commented on Apr 26, 2016

    @liady

    @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.js
    var nodeExternals = require('webpack-node-externals');
    ...
    module.exports = {
        ...
        externals: [nodeExternals({
            modulesFromFile: true
        })], // in order to ignore all modules in package.json when bundling
        ...
    };
  29. hinell commented on Jan 29, 2017

    @hinell

    Here is my way to prevent node_modules from being bundled:

    { externals: [function (context,req,cb) {
            !/^\./.test(req)
              ? cb(null,req)
              : cb(null,false);
      }] 
    }

    Output bundle requests then look like this (require isn't declared in result bundle):

    /***/ (function(module, exports) {
    
    module.exports = require("path");
    
    /***/ }),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions