Kousha
Kousha

Reputation: 36189

Webpack to export a CLI environment variable to window object

Is there a way to expose an environment variable to the window object using Webpack?

For example, doing REALM=stage npm run start I want webpack to read REALM and provide it as window.__realm so my React app can read it from the window object.

Upvotes: 1

Views: 1858

Answers (3)

Slbox
Slbox

Reputation: 13108

@Andrey answer is the closest answer I've found anywhere, but not quite there.

This is what finally worked for me:

In your Webpack config:

new webpack.DefinePlugin({'process.env.FOO': JSON.stringify(true)})

Somewhere in the top level of one of your project's source files:

window.FOO = process.env.FOO; // The necessity to do this seriously limits the utility of webpack.DefinePlugin in my view, but what can you do?

Even though process & process.env may be undefined when you try to access them, the value will be assigned to window.FOO successfully.

console.log(window.FOO) // outputs: true

Upvotes: 0

Andrey
Andrey

Reputation: 311

You can use DefinePlugin, documentation: https://webpack.js.org/plugins/define-plugin/

In webpack config you need to use plugin:

new webpack.DefinePlugin({FOO: '123'})

In code you need assign to variable:

window.FOO = process.env.FOO;

When webpack will compile code, it will replace process.env.FOO with '123'; So after compilation you will get:

window.FOO = '123';

Upvotes: 2

Chris B.
Chris B.

Reputation: 5763

You can use libraryTarget in your output config object:

output: {
    library: "__realm",
    libraryTarget: "window"
}

And access it with window.__realm.

Upvotes: 0

Related Questions