作者:LKD2008_561 | 来源:互联网 | 2022-11-30 09:53
我正在使用Next.js构建一个React SSR应用程序。
我希望能够在客户端访问NODE_ENV,因为这将告诉我的应用程序要使用哪些API端点。
我正在努力为此找到一个体面的方法。第一次在服务器上呈现页面时,我想将NODE_ENV定义为窗口变量,然后在进行API调用的辅助函数中,检查是否在服务器或客户端上调用了代码,并根据需要使用window或process.env变量。
有没有人对这个问题有好的解决方案。这肯定是一个普遍的问题,但是我找不到任何好的解决方案。
1> Darryl R. No..:
1.您可以将其包含在webpack配置中(使用dotenv-webpack依赖项):
require('dotenv').config()
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
webpack: (config) => {
config.plugins = config.plugins || []
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, '.env'),
systemvars: true
})
]
return config
}
}