Build time ENV vars / constants
See original GitHub issue❔ Question
- Is it possible to define global constants at build time, the same way you would do that with webpack’s DefinePlugin?
- Is it also possible to filter out parts of the application code based on these constants?
🔦 Context
I would like to be able to set global variables by means of ENV variables set either in an .env file or on the command line. These should be inlined into the code at compile time, and as such the user should have no influence over them at run time. This differs from the ENV vars that parcel already support, which can be changed at run time.
Look at the code sample below for an example. It is a contrived example but the method is quite powerful for stitching together/removing code for multiple versions of an app, but keeping one code base.
💻 Code Sample
Below is an example of how I would do this in webpack.
Defining the constants in the webpack DefinePlugin:
new webpack.DefinePlugin({
ICE_CREAM: JSON.stringify(process.env.ICE_CREAM === "true")
});
In webpack I can filter out the certain parts of the code based on these constants:
if (ICE_CREAM) {
console.log("yay! we have ice cream!");
} else {
console.log("dang! no ice cream!");
}
Since webpack inlines the values of the constants and removes dead code, this would translate after building (when running webpack with env var ICE_CREAM=“true”) to:
if (true) { console.log("yay! we have ice cream!"); }
and to the following when the env var ICE_CREAM is not set:
if (false) {} else { console.log("dang! no ice cream!"); }
(I am not sure that this is exactly how it is translated in webpack, but you get the idea) 😃
🌍 Your Environment
Software | Version(s) |
---|---|
Parcel | 1.12.3 |
Node | 12.1.0 |
Yarn | 1.15.2 |
Operating System | os x |
KUDO’s
Thanks for an awesome piece of software! Parcel really improved my workflow tremendously. 👏
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (2 by maintainers)
Another possible solution: parcel-plugin-elecron-dotenv. The babel plugin wasn’t ideal for us; we wanted something that exactly mimicked the behavior of Parcel for browser targets.
Ok, clear. Thanks for the pointer, I looked myself for this in the codebase, but couldn’t pinpoint it.
For people in the same situation as described above, looking for a solution to this: You can use this babel plugin: https://babeljs.io/docs/en/babel-plugin-transform-inline-environment-variables. It will inline ENV variables with a whitelist.
Thanks for the help, closing!