我有一个文件,我想要同时拥有 Node.js 和浏览器代码。
Node.js 代码不应在浏览器中可见。
webpack 可以根据环境从文件中排除代码吗?
有点像 C 预处理指令。#if #else, etc
.
我知道 Webpack 非常密集地解析代码,这让我认为它可以。
约束
Node.js 代码无法进入浏览器,因为它可能包含敏感的配置选项。
我希望浏览器和节点代码在同一个文件中。我知道我可以使用
webpack.IgnorePlugin
忽略文件基础上的要求,或者将共享代码放在浏览器文件中并要求来自服务器(我现在正在这样做),但我想知道是否有可能拥有代码并排在同一个文件中。
编辑:这是我正在尝试做的一个例子。
export class FooPlugin {
$name = 'foo-plugin'
register(app) {
const app = koa()
app.get('/foo', () => { this.send('foo') })
app.set('SECRET STUFF!')
app.start()
this.shared()
}
shared(app) {
// browser things - isomorphic react router routes, etc.
}
registerBrowser(app) {
this.shared()
}
}
// This is called in another file depending on the environment.
if (!isBrowser) {
(new FooPlugin).register(app)
} else {
(new FooPlugin).registerBrowser(app)
}