Typescript dotenv 在被变量访问时返回 undefined
Typescript dotenv returning undefined when accessed by a variable
我已经设置了一个助手来访问我的 process.env,如下所示:
export const env = (key: string, def: any = null): string|any => {
console.log(process.env["APP_ENV"], process.env[key], key === "APP_ENV")
// @ts-ignore
if ( process.env[key] instanceof String && process.env[key].length) {
return process.env[key]
}
return def
}
这已通过插件注入到我的所有模块中:
plugins: [
new Dotenv(),
new webpack.ProvidePlugin({
env: ['./plugins/config_helper', 'env'],
})
]
当我以 env("APP_ENV")
访问它时,我从调试打印中得到了一个莫名其妙的结果。
develop undefined true
有人可以解释这种行为吗?更具体地说,当我通过变量访问它时,为什么 process.env 会产生 undefined?
对于问题的原因部分,请查看此答案:
下面是我在我的应用程序中使用的解决方案,请注意,我对我的所有环境变量都使用了前缀 REACT_APP_
。
webpack.config.js:
require('dotenv').config()
const getReactEnvs = () => {
const envs = {}
Object.keys(process.env).forEach(env => {
if(env.startsWith('REACT_APP_')) envs[env] = process.env[env]
})
return envs
}
module.exports = [
new ProvidePlugin({
process: 'process/browser',
}),
new DefinePlugin({
'process.env': JSON.stringify({ ...getReactEnvs() }),
}),
]
我已经设置了一个助手来访问我的 process.env,如下所示:
export const env = (key: string, def: any = null): string|any => {
console.log(process.env["APP_ENV"], process.env[key], key === "APP_ENV")
// @ts-ignore
if ( process.env[key] instanceof String && process.env[key].length) {
return process.env[key]
}
return def
}
这已通过插件注入到我的所有模块中:
plugins: [
new Dotenv(),
new webpack.ProvidePlugin({
env: ['./plugins/config_helper', 'env'],
})
]
当我以 env("APP_ENV")
访问它时,我从调试打印中得到了一个莫名其妙的结果。
develop undefined true
有人可以解释这种行为吗?更具体地说,当我通过变量访问它时,为什么 process.env 会产生 undefined?
对于问题的原因部分,请查看此答案:
下面是我在我的应用程序中使用的解决方案,请注意,我对我的所有环境变量都使用了前缀 REACT_APP_
。
webpack.config.js:
require('dotenv').config()
const getReactEnvs = () => {
const envs = {}
Object.keys(process.env).forEach(env => {
if(env.startsWith('REACT_APP_')) envs[env] = process.env[env]
})
return envs
}
module.exports = [
new ProvidePlugin({
process: 'process/browser',
}),
new DefinePlugin({
'process.env': JSON.stringify({ ...getReactEnvs() }),
}),
]