如何在与webpack/browsrify绑定时排除代码路径
How can I exclude code path when bundling with webpack/browserify?
我有一个可以与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
和本机节点库排除在捆绑之外,您需要:
- 将
target: 'node'
添加到您的webpack.config.js
中。这将从绑定中排除本机节点模块(路径、fs等) - 使用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');
});
}
有关更多信息和示例演示用法,请参阅代码拆分。
- 在VanillaJS中模拟模型双向数据绑定
- 无法通过数组映射绑定
- 主干-不管怎样,检查事件以前是否绑定过
- 用于搜索的聚合物嵌套绑定
- Angular:更新一次性绑定的数据
- 如何使用ngrepeat和双向绑定获得指令的隔离范围
- react.js中的密钥绑定
- 使用regex的jquery keydown绑定不会验证撇号和句点
- 将事件处理程序绑定到任何可能的事件
- AngularJS指令只识别双向绑定类型
- Telerik rad组合框多列数据绑定
- 对API数据使用声明性绑定
- 如何销毁/删除/取消绑定SnapSVG.js
- 在D3.js中,有没有任何方法可以将x和y方向上的滚动事件绑定到平移svg
- 数据绑定:'系统Char'不包含名为'xxxxx'
- react组件中的绑定方法
- 如何将ngrepeat下的ngmodel绑定到$scope
- WinJS内联绑定语法
- 为什么Angular 1.5双向绑定在将作用域变量传递给组件绑定时失败
- Knockoutjs:同时使用单击和选中绑定时绑定评估的顺序