我正在构建一个在浏览器和服务器端 Node 中使用共享 React 组件的应用。
现在,我正在使用 Marty.js 来执行此操作:
function getUser() {
if (Marty.isBrowser) {
/* Get user using some client method */
} else {
/* otherwise, use some secret server code */
}
}
我通过 Browserify 将这些功能捆绑在一起,因此它们可以在客户端和服务器上运行。
我想做的是从包中完全删除 else
block ,这样我就不会泄露敏感的服务器端代码。
有没有办法从包中排除代码块?
最佳答案
我会创建单独的模块,一个用于浏览器,一个用于服务器。然后在你的 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.
关于javascript - browserify - 排除代码块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30442220/