browserify - 排除代码块?

browserify - exclude code blocks?

我正在构建一个在浏览器和服务器端 Node 中使用共享 React 组件的应用程序。

现在,我正在使用 Marty.js 来执行此操作:

function getUser() {
    if (Marty.isBrowser) {
        /* Get user using some client method */  
    } else {
        /* otherwise, use some secret server code */
    }
}

我正在通过 Browserify 捆绑这些功能,因此它们可以 运行 在客户端和服务器上。

我想做的是从捆绑包中完全删除 else 块,这样我就不会泄露敏感的服务器端代码。

有没有办法从包中排除代码块?

我会创建单独的模块,一个用于浏览器,一个用于服务器。然后在你的 package.json 中,你告诉 browserify 使用浏览器模块:

"browser": {
    "./path/to/node-module.js": "./path/to/browser-module.js"
}

现在,无论您在哪里调用 require('path/to/node-module'),browserify 都会加载另一个模块。


来自 docs 的更多信息:

browser field

There is a special "browser" field you can set in your package.json on a per-module basis to override file resolution for browser-specific versions of files.

For example, if you want to have a browser-specific module entry point for your "main" field you can just set the "browser" field to a string:

"browser": "./browser.js"

or you can have overrides on a per-file basis:

"browser": {
  "fs": "level-fs",
  "./lib/ops.js": "./browser/opts.js"
}

Note that the browser field only applies to files in the local module, and like transforms, it doesn't apply into node_modules directories.

如何将代码放入一个模块中,例如 UserServer,然后在为客户端编译时排除该模块?您的代码变为:

function getUser() {
    if (Marty.isBrowser) {
        /* Get user using some client method */  
    } else { 
       require('UserServer').getUser();
    }
}

Browserify 提供以下选项以从捆绑包中排除文件:

--exclude, -u  Omit a file from the output bundle. Files can be globs.

更明确地说明您的意图,并将您的代码放在他们自己的文件中:

function getUser(options, callback) {
  var fn;
  if (Marty.isBrowser) {
      fn = require("./lib/users/get.browser");
  } else {
      fn = require("./lib/users/get.server");
  }
  fn(options, callback);
}

然后作为 browserify 选项,你可以说 "replace require("./lib/users/get.server") with this variable instead, when you see it: ..." 这样你就不会在为浏览器构建时在该服务器文件中构建。

但是,如果 getUser 可以根据它所在的位置执行不同的操作 运行,则感觉您在这里做错事情的可能性要大得多:也许 getUser 应该是从浏览器,但没有更多信息,这总是很难确定。

虽然我不确定 Browserify 是否可行,但您可以使用 Webpack 的 DefinePlugin

来自docs(稍作修改):

Example:

new webpack.DefinePlugin({
    DEBUG: false,
    PRODUCTION: true,
    ...
})

...

Example:

if(DEBUG)
    console.log('Debug info')
if(PRODUCTION)
    console.log('Production log')

After passing through webpack with no minification results in:

if(false)
    console.log('Debug info')
if(true)
    console.log('Production log')

and then after a minification pass results in:

console.log('Production log')

您可以使用环境变量 envify and uglify 来执行此操作。

if ('browser' === process.env.ENVIRONMENT) {
  ...
}
else {
  ...
}

在构建浏览器时设置 process.env.ENVIRONMENT = 'browser',使用 envify 转换将对 process.env 的引用替换为它们的当前值,然后 uglify 将执行死代码消除以删除永远不会被删除的分支命中.