首页 > 解决方案 > Webpack 和环境变量评估?

问题描述

我正在使用 webpack 捆绑我的前端应用程序并从 heroku 加载环境变量。

环境变量在函数内部使用时可以解析,但在外部评估并分配给 const 时不能解析:

import...

   /*This line will fail with : 'VM286683:1 Uncaught SyntaxError: Unexpected token u in JSON at position 
    0 at JSON.parse (<anonymous>)'*/
const geoApiSecretKey = JSON.parse(process.env.GEO_API_SECRET!);


function getGpsPosition() {

  //That one will parse the JSON without any issue
  const local_geoApiSecretKey = JSON.parse(process.env.GEO_API_SECRET!);
  ...
}

我的 webpack 配置使用DefinePlugin加载环境变量:

...
plugins: [
        new CheckerPlugin(),
        new HtmlWebpackPlugin({template: 'index.html.ejs',}),
        new webpack.DefinePlugin({
            'process.env': {
                'GEO_API_SECRET': JSON.stringify(process.env.GEO_API_SECRET)
            }
        })
    ],

我猜它与 webpack 或 heroku 无关。我只是错过了一些我在这里找不到的东西。谢谢您的帮助。

标签: javascriptherokuwebpackenvironment-variables

解决方案


变量在另一个文件中被覆盖,从而改变了它的性质


推荐阅读