user2190690
user2190690

Reputation: 2034

Pass environment variable from package.json to React app

I'm building a React / Node / Express / Webpack (2.2.1) application and would like to know how to approach the following:

I would like an environment variable to be visible in the React client - the purpose being for certain api requests to use either the localhost or otherwise the IP address of the production server.

Is it possible to get an environment variable from running a script in package.json, to the webpack build, and then compiled and visible in the bundled javascript.

So in terminal run:

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

or

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

and the script definition being something like:

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

...help greatly appreciated

Upvotes: 1

Views: 5539

Answers (1)

holi-java
holi-java

Reputation: 30686

CLI with --define option

--define option using webpack.DefinePlugin so you must pass a string value into app.

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

config webpack.config.js plugins and pass process.env into app

APP_ENV="development" npm run build-dev nodejs set environment variables at the head of command.you can use webpack.EnvironmentPlugin to expose process.env into bundle.js that I have tested.

Demo
"scripts": {
     "build-dev": "APP_ENV=development webpack"
 }
Test
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/);
    }));
});

Upvotes: 2

Related Questions