Search code examples
javascriptwebpackparceljs

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.


Solution

  • 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.