How can I exclude code path when bundling with webpack/browserify?

后端 未结 4 710
再見小時候
再見小時候 2021-02-12 09:27

I have a library that can be used with both node.js and the browser. I am using CommonJS then publishing for the web version using webpack. My code looks like this:



        
相关标签:
4条回答
  • 2021-02-12 09:57

    This worked best for me

    var _process;
    
    try {
        _process = eval("process");  // avoid browserify shim
    } catch (e) {}
    
    var isNode = typeof _process==="object" && _process.toString()==="[object process]";
    

    as Node will return true and not only will the browser return false, but browserify will not include its process shim when compiling your code. As a result, your browserified code will be smaller.

    Edit: I wrote a package to handle this more cleanly: broquire

    0 讨论(0)
  • 2021-02-12 10:14

    In order to exclude node_modules and native node libraries from being bundled, you need to:

    1. Add target: 'node' to your webpack.config.js. This will exclude native node modules (path, fs, etc.) from being bundled.
    2. Use webpack-node-externals in order to exclude all other node_modules.

    So your result config file should look like:

    var nodeExternals = require('webpack-node-externals');
    ...
    module.exports = {
        ...
        target: 'node', // in order to ignore built-in modules like path, fs, etc. 
        externals: [nodeExternals()], // in order to ignore all modules in node_modules folder 
        ...
    };
    
    0 讨论(0)
  • 2021-02-12 10:20

    You can use require.ensure for bundle splitting. For example

    if (typeof window !== 'undefined') {
        console.log("Loading browser XMLHttpRequest");
    
        require.ensure([], function(require){
    
            // require.ensure creates a bundle split-point
            require('./adapters/xhr');
        });
    } else if (typeof process !== 'undefined') {
        console.log("Loading node http");
    
        require.ensure([], function(require){
    
            // require.ensure creates a bundle split-point
            require('./adapters/http');
        });
    }
    

    See code splitting for more information and a sample demo usage here

    0 讨论(0)
  • 2021-02-12 10:24

    You may use IgnorePlugin for Webpack. If you are using a webpack.config.js file, use it like this:

    var webpack = require('webpack')
    
    var ignore = new webpack.IgnorePlugin(/^(canvas|mongoose|react)$/)
    
    module.exports = {
      //other options goes here
      plugins: [ignore]
    }
    

    To push it further, you may use some flags like process.env.NODE_ENV to control the regex filter of IgnorePlugin

    0 讨论(0)
提交回复
热议问题