webpack-inject-environment-variables
v1.0.0
Published
A webpack plugin extracted from Facebook create-react-app that allows you to inject environment variables to a javascript client during CI
Downloads
3
Maintainers
Readme
Webpack Inject Environment Plugin
A webpack plugin extracted from Facebook create-react-app that allows you to inject environment variables to a javascript client during continuous integration. This plugin can be used in any context, for a shared javascript library or React application or Vue application.
Installation
npm install --save-dev webpack-inject-environment-variables
Usage
Require the plugin with your Webpack configuration (or applicable extensions if you're using a framework) and then add a new InjectEnvironmentPlugin
to the plugins.
const InjectEnvironmentPlugin = require('webpack-inject-environment-variables');
module.exports = {
plugins: [
new InjectEnvironmentPlugin({regex: /^MY_NAMESPACE/i}),
]
}
The InjectEnvironmentPlugin
class takes a configuration object with two arguments:
| Argument | Type | Default | Purpose |
| --- | --- | --- | --- |
| regex
| Regex | | All environment variables on the system that are read by the plugin will be filtered by their keys against the regex pattern you provide. Only environment variables starting with MY_NAMESPACE
in the above example will be considered with that regex. MY_NAMESPACE_ID
, MY_NAMESPACE_NAME
will be, MY_ID
will not. You can change this regex to be whatever you want. |
| environment
| string | production | Specify the default environment for the script to run in. |
Purpose
This plugin allows you to store environment-specific or sensitive data in a .env
file or within the build environments themselves and let the application access their values even though it is being run in the browser. The alternative to using environment variables for this use case is to have multiple hard-coded configurations with some environment detection logic - which can become messy. With this solution you inject the values that change per project and the application can become agnostic of its environment.
This plugin works best if you create a simple Docker environment that uses your .env
file. The environment variables don't need to be available on any production server, only on the CI build server or when you build a distributable package for your project with Webpack.
Origin
Most of this code was taken from the Facebook create-react-app build scripts and refactored to be decoupled from React logic and other plugins they use in their scafolding tool. In addition, the new ES6 syntax makes the code more modular for future modifications should they be necessary.
Contributing and Distribution
This plugin is licensed as MIT, all contributions are welcome for any edge cases this plugin might not cover.
A distributable can be created by running npm run build
in a Node environment with version 12. Use npm pack
and install the resulting tgz file in your project to test your modifications.