我怎样才能用的WebPack / browserify捆绑时不包括code路径? [英] How can I exclude code path when bundling with webpack/browserify?

查看:213
本文介绍了我怎样才能用的WebPack / browserify捆绑时不包括code路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可以与node.js的和浏览器中使用的库。我使用CommonJS的发布再使用的WebPack网页版。我的code是这样的:

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:

// 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 与一直以来它的依赖。这导致巨大的文件,该文件是不是最佳的浏览器的性能。

The problem I am encountering is that when I run webpack (browserify would do the same) the generated output includes http along with all it's dependencies. This results in a HUGE file which is not optimal for browser performance.

我的问题是我怎么能运行的模块时,打捆排除节点code路径?我解决了这个临时使用的WebPack的外部组件和包括'./适配器/ HTTP 时,只返回undefined。这并没有解决,而其他开发人员使用CommonJS的取决于我的图书馆用例。他们建立将结束与同样的问题,除非他们使用类似的配置排除

My question is how can I exclude the node code path when running a module bundler? I solved this temporarily by using webpack's externals and just returning undefined when including './adapters/http'. This doesn't solve the use case where other developers depend on my library using CommonJS. Their build will end up with the same problem unless they use similar exclude config.

我看用envify,只是不知道是否有其他/更好的解决方案。

I've looked at using envify, just wondering if there is another/better solution.

谢谢!

推荐答案

您可以使用 IgnorePlugin 的WebPACK中。如果您使用的是webpack.config.js文件,使用这样的:

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]
}

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

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

这篇关于我怎样才能用的WebPack / browserify捆绑时不包括code路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆