gatsby-env-variables
Webpack feature to provide your custom environment variables in client side
Use `BUILD_ENV` to chose wich environment file to load and `THEME` to chose theme variables together
Install
$ npm i gatsby-env-variables
or
$ yarn add gatsby-env-variables
How to use
Add the plugin to your gatsby-config.js
.
moduleexports = plugins: `gatsby-env-variables`
Create your's environment.js
files inside env/
folder, on root of your project, file index.js
will be the file with variables shared between multiple environments, if you chose other env, these variables will be merged
project/├── env/ ├── index.js ├── development.js ├── staging.js └── production.js
index.js
moduleexports = API_ROOT: "example.com" CARDS: "/cards"
staging.js
moduleexports = API_ROOT: "stg.example.com"
Run your yarn/npm script with BUILD_ENV
variable to chose your environment, default selected is development
package.json
BUILD_ENV=staging yarn start
Use in client-side
Global variables
/* globals API_ROOT, CARDS */ { const cardsURL = API_ROOT + CARDS // stg.example.com/cards }
If you don't want to use /* globals */
in each file, just create an empty .eslintrc
file in your project folder. If you are using eslint, just disable the no-undef
rule.
Importing variables
{ const cardsURL = API_ROOT + CARDS // stg.example.com/cards }
Using themes
You can have multiple themes, with multiple environments, just put your variables inside the name of theme, and use THEME=example
on your running script
staging.js
moduleexports = API_ROOT: "stg.example.com" dark: CARDS: "/dark_cards"
package.json
THEME=dark BUILD_ENV=staging yarn start
Use in client-side
{ const cardsURL = API_ROOT + CARDS // stg.example.com/dark_cards }
Nested Objects
String values are not required, you can use nested objects too
staging.js
moduleexports = API: CARDS: "/cards" dark: API_ROOT: "darkexample.com"
Async variables
If you have to put dynamic variables in you environment, like values coming from API or something like this, you can export an promise
staging.js
moduleexports = async { const ROOT_API = "example.com" const CARDS = "/cards" const response = await const ACTIVE_CARDS = await response const envs = ROOT_API CARDS ACTIVE_CARDS dark: CARDS: "/dark_cards" orange: CARDS: "/orange_cards" }
Options
envFolderPath
This options allows you to specify which folder will stay your .env
files
Example:
moduleexports = plugins: resolve: `gatsby-env-variables` options: envFolderPath: `src/env/`
project/├── src/ ├── env/ ├── index.js ├── development.js ├── staging.js └── production.j
Or you can use this option to rename to config/
folder too
Example:
moduleexports = plugins: resolve: `gatsby-env-variables` options: envFolderPath: `config/`
project/├── config/ ├── index.js ├── development.js ├── staging.js └── production.jn
Further reading
Check out the DefinePlugin section of the Webpack config documentation for more information.