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.
Parcel.js (parceljs.org) is exactly what many beginning to intermediate developers want: A simple, low-configuration bundler that you can get up and running with quickly. I hope this Parcel tutorial will provide an easy-to-follow introduction to this tool.
For a basic project setup, I’m going to use Parcel.js on an index.html file that points to a primary JavaScript file called index.js (as shown in the package.json file). This HTML file will serve as my Parcel entry point. My HTML file will have a script element that points to my JavaScript file, so it will look something like this:
Using this watcher Parcel watches every file in your project root (including all node_modules ). Based on events and metadata from these files, Parcel determines which files need to be rebuilt.
You can install Parcel.js in your terminal using Yarn or npm. For this tutorial, I’ll use npm. Here’s the command to install it globally so you can use it on any project: The -g flag installs it globally.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With