我正在构建一个应用程序,它的服务器在
node
中运行,客户端在浏览器中运行。它们都依赖于一个通用的实用程序文件。该实用程序文件需要一个特定部分来展示服务器和客户端之间的不同行为。
我在这里试图完成的(极端)简化版本是:
server.js
import util from './util.js`;
const x = await util.foo();
// do server-side things with `x`
client.js
import util from './util.js`;
const x = await util.foo();
// do client-side things with `x`
util.js
async function foo() {
if (process.env.CLIENT_BUILD === 'true') {
console.log('WARNING results in run-time error if this runs on server.');
} else {
console.log('WARNING results in build/bundle-time error if this is done on a client build.');
}
}
对于服务器来说,这不是问题,因为环境变量已被拾取,并且执行了适当的分支。
但是,对于客户端来说,这是一个问题,因为在捆绑时,带有
console.log
的行甚至不需要由 webpack 处理 - 并且完全跳过。
我发现了一些参考资料,表明完成此操作的方法过去是通过 process.env
来实现的...但是这在实践中似乎不起作用,并且 webpack 尝试构建/捆绑 if
条件的两个分支声明。适用于 Webpack 5 的当前建议是什么? (具体来说,我通过
[email protected]
使用
@vue/[email protected]
)参考资料:
import
, 与 webpack 构建时提示结合使用,
webpackIgnore
。(1) 将仅服务器组件拆分为单独的文件。
(2) 使用
import
函数
(又名“动态导入”,不要与
import
语句混淆)来引用此单独的文件。(3) 在/* webpackIgnore: true */
的左括号和文件名之间添加内嵌注释
import
。示例:
util.js
async function foo() {
if (process.env.CLIENT_BUILD === 'true') {
console.log('WARNING results in run-time error if this runs on server.');
} else {
const { serverOnlyBit } = await import(
/* webpackIgnore: true */
'./server-only-bit.js'
);
serverOnlyBit();
}
}
server-only-bit.js
export function serverOnlyBit() {
console.log('WARNING results in build/bundle-time error if this is done on a client build.');
}