将环境变量从package.json传递到React app

时间:2017-03-04 14:06:09

标签: javascript node.js reactjs webpack

我正在构建一个React / Node / Express / Webpack(2.2.1)应用程序,并想知道如何处理以下内容:

我希望环境变量在React客户端中可见 - 目的是使某些api请求使用localhost或生产服务器的IP地址。

是否有可能获得一个环境变量,从在package.json中运行脚本到webpack构建,然后在捆绑的javascript中编译和显示。

所以在终端运行中:

npm run build-dev // pass to Webpack something like APP_ENV="development"

npm run build-prod // pass to Webpack something like APP_ENV="production"

并且脚本定义类似于:

"scripts": {
    "build-dev": "webpack --define APP_ENV='development'"
}

...非常感谢

1 个答案:

答案 0 :(得分:2)

CLI with --define option

使用--define

webpack.DefinePlugin选项,因此您必须将字符串值传递到app。

演示
"scripts": {
   "build-dev": "webpack --define APP_ENV=\"'development'\""
}

配置webpack.config.js插件并将process.env传递到app

APP_ENV="development" npm run build-dev nodejs在命令的头部设置环境变量。您可以使用webpack.EnvironmentPlugin将process.env暴露给我测试过的bundle.js。

演示
"scripts": {
     "build-dev": "APP_ENV=development webpack"
 }
测试
describe('string-replace-webpack-loader', () => {
    it('environment exists', () => {
        expect(process.env.APP_ENV).toBe('dev');
    });

    it('replace environment variables', compile({
        entry: './env.js',
        plugins: [
            new webpack.EnvironmentPlugin(Object.keys(process.env))
        ]

    }).then(({log}, files) => {
        expect(files['/bundle.js']).toMatch(/(["'])dev\1/);
    }));
});