Jonathan M. Hethey
Jonathan M. Hethey

Reputation: 714

Expose Environment in Parceljs?

I'm trying to expose a variable when building with Parcel.js, similar to the Webpack DefinePlugin but I haven't found out how to do it.

In development I want my API host to be different from my production one, so:

//development:
API_URL="http://localhost:8900/"

//production:
API_URL="/"

Currently Parcel supports the module.hot switch, which I could abuse for that since the hot module reloading is only enabled in development, but it would be nice to have a better way for this.

I also can check if window.location.hostname is localhost, but it's a workaround.

Upvotes: 7

Views: 4627

Answers (1)

Tadas Antanavicius
Tadas Antanavicius

Reputation: 5410

For anyone still seeking an answer to this:

You can use Parcel.js's .env file support (by way of the dotenv package), added in 1.5.0 (2018-01-23).

No additional config needed. Just make your .env files separated by the appropriate NODE_ENV (production, development, etc) and you can access variables via process.env.VARIABLE_NAME. In your case, you could do:

.env.development

API_URL=http://localhost:8900/

.env.production

API_URL=/

And then use it by calling process.env.API_URL (no further imports needed) in your code as needed.

Upvotes: 20

Related Questions