如何在与webpack/browsrify绑定时排除代码路径

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

本文关键字:定时 绑定 排除 代码 路径 browsrify webpack      更新时间:2023-09-26

我有一个可以与node.js和浏览器一起使用的库。我使用CommonJS,然后使用webpack发布web版本。我的代码如下:

// For browsers use XHR adapter
if (typeof window !== 'undefined') {
  // This adapter uses browser's XMLHttpRequest
  require('./adapters/xhr');
}
// For node use HTTP adapter
else if (typeof process !== 'undefined') {
  // This adapter uses node's `http`
  require('./adapters/http');
}

我遇到的问题是,当我运行webpack时(browserfy也会这样做),生成的输出包括http及其所有依赖项。这将导致一个庞大的文件,该文件对于浏览器性能而言不是最佳的。

我的问题是,在运行模块打包程序时,如何排除节点代码路径?我通过使用webpack的externals暂时解决了这个问题,并且在包含'./adapters/http'时只返回undefined。这并不能解决其他开发人员使用CommonJS依赖我的库的用例。除非他们使用类似的exclude配置,否则他们的构建最终会出现同样的问题。

我考虑过使用envify,只是想知道是否还有其他/更好的解决方案。

谢谢!

您可以将IgnorePlugin用于Webpack。如果你使用的是webpack.config.js文件,可以这样使用:

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

为了进一步推动它,您可以使用一些标志,如process.env.NODE_ENV来控制IgnorePlugin 的正则表达式过滤器

为了将node_modules和本机节点库排除在捆绑之外,您需要:

  1. target: 'node'添加到您的webpack.config.js中。这将从绑定中排除本机节点模块(路径、fs等)
  2. 使用webpack节点外部以排除所有其他node_modules

所以你的结果配置文件应该看起来像:

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 
    ...
};

这对我来说效果最好

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

因为Node将返回true,而且浏览器不仅会返回false,而且在编译代码时browserfy将不包括其process填充程序。因此,您已浏览的代码将更小。

编辑:我写了一个包来更干净地处理这个问题:broquire

您可以使用require.ensure进行束拆分。例如

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');
    });
}

有关更多信息和示例演示用法,请参阅代码拆分。