如何在使用webpack/browserify打包时排除代码路径?

23

我有一个可以在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(browserify也会有同样的情况),生成的输出包括了http及其所有依赖项。这导致文件非常巨大,不利于浏览器性能。

我的问题是,在运行模块打包程序时如何排除Node代码路径?我通过使用webpack的外部(externals)并在包含'./adapters/http'时返回未定义(undefined)来暂时解决了这个问题。但这无法解决其他开发人员使用CommonJS依赖于我的库的情况。他们的构建将面临相同的问题,除非他们使用类似的排除配置。

我已经尝试使用envify,只是想知道是否还有另一个/更好的解决方案。

谢谢!

4个回答

28

您可以在Webpack中使用IgnorePlugin。如果您正在使用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的正则表达式过滤器。

5
为了排除node_modules和本机节点库被捆绑,您需要:
  1. 在您的webpack.config.js中添加target: 'node'。这将排除本机节点模块(path, fs等)。
  2. 使用webpack-node-externals,以排除所有其他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 
    ...
};

1

这对我来说效果最好

var _process;

try {
    _process = eval("process");  // avoid browserify shim
} catch (e) {}

var isNode = typeof _process==="object" && _process.toString()==="[object process]";

作为 Node,它将返回“true”,而浏览器将不仅返回“false”,browserify在编译代码时也不会包含其“process”补丁。结果,您的 browserified 代码将更小。 编辑:我编写了一个包来更清洁地处理这个问题:broquire

0

您可以使用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');
    });
}

查看 代码分割 获取更多信息,样例演示用法在这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接