Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for env files #1462

Merged
merged 2 commits into from
Jul 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/docs/environment-variables.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
title: "Environment Variables"
---

You can easily provide environment variables to your site. Just add a `.env.development` and/or `.env.production` file in your root folder for development or production builds respectively. The environment variables are embedded during build time using Webpack's [DefinePlugin](https://webpack.js.org/plugins/define-plugin/). Because these variables are provided at build time, you will need restart your dev server or rebuild your site after changing them.

## Example

```
# Example .env.development file

API_URL=https://dev.example.com/api
```

```
# Example .env.production file

API_URL=https://example.com/api

```

These variables will be available to your site as `process.env.API_URL`.

> You can not override certain environment variables as some are used internally for optimizations during build

Reserved environment variables:

- `NODE_ENV`
- `PUBLIC_DIR`
1 change: 1 addition & 0 deletions packages/gatsby/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"css-loader": "^0.26.1",
"debug": "^2.6.0",
"detect-port": "^1.2.1",
"dotenv": "^4.0.0",
"eventemitter2": "^4.1.0",
"express": "^4.14.0",
"express-graphql": "^0.6.6",
Expand Down
60 changes: 30 additions & 30 deletions packages/gatsby/src/utils/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { uniq, some } from "lodash"
import fs from "fs"
import path from "path"
import webpack from "webpack"
import dotenv from "dotenv"
import Config from "webpack-configurator"
import ExtractTextPlugin from "extract-text-webpack-plugin"
import StaticSiteGeneratorPlugin from "static-site-generator-webpack-plugin"
Expand Down Expand Up @@ -41,6 +42,30 @@ module.exports = async (
const stage = suppliedStage
const babelConfig = await genBabelConfig(program, babelStage)

function processEnv(stage, defaultNodeEnv) {
debug(`Building env for "${stage}"`)
const env = process.env.NODE_ENV ? process.env.NODE_ENV : `${defaultNodeEnv}`
const envFile = path.join(process.cwd(), `./.env.${env}`)
let parsed = {}
try {
parsed = dotenv.parse(fs.readFileSync(envFile, { encoding: `utf8` }))
} catch(e) {
if (e && e.code !== `ENOENT`) {
console.log(e)
}
}
const envObject = Object.keys(parsed).reduce((acc, key) => {
acc[key] = JSON.stringify(parsed[key])
return acc
}, {})

// Don't allow overwriting of NODE_ENV, PUBLIC_DIR as to not break gatsby things
envObject.NODE_ENV = JSON.stringify(env)
envObject.PUBLIC_DIR = JSON.stringify(`${process.cwd()}/public`)

return envObject
}

debug(`Loading webpack config for stage "${stage}"`)
function output() {
switch (stage) {
Expand Down Expand Up @@ -127,12 +152,7 @@ module.exports = async (
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(
process.env.NODE_ENV ? process.env.NODE_ENV : `development`
),
PUBLIC_DIR: JSON.stringify(`${process.cwd()}/public`),
},
"process.env": processEnv(stage, `development`),
__PREFIX_PATHS__: program.prefixPaths,
__PATH_PREFIX__: JSON.stringify(store.getState().config.pathPrefix),
}),
Expand All @@ -154,12 +174,7 @@ module.exports = async (
return [
new StaticSiteGeneratorPlugin(`render-page.js`, pages),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(
process.env.NODE_ENV ? process.env.NODE_ENV : `development`
),
PUBLIC_DIR: JSON.stringify(`${process.cwd()}/public`),
},
"process.env": processEnv(stage, `development`),
__PREFIX_PATHS__: program.prefixPaths,
__PATH_PREFIX__: JSON.stringify(store.getState().config.pathPrefix),
}),
Expand All @@ -168,12 +183,7 @@ module.exports = async (
case `build-css`:
return [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(
process.env.NODE_ENV ? process.env.NODE_ENV : `production`
),
PUBLIC_DIR: JSON.stringify(`${process.cwd()}/public`),
},
"process.env": processEnv(stage, `production`),
__PREFIX_PATHS__: program.prefixPaths,
__PATH_PREFIX__: JSON.stringify(store.getState().config.pathPrefix),
}),
Expand All @@ -183,12 +193,7 @@ module.exports = async (
return [
new StaticSiteGeneratorPlugin(`render-page.js`, pages),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(
process.env.NODE_ENV ? process.env.NODE_ENV : `production`
),
PUBLIC_DIR: JSON.stringify(`${process.cwd()}/public`),
},
"process.env": processEnv(stage, `production`),
__PREFIX_PATHS__: program.prefixPaths,
__PATH_PREFIX__: JSON.stringify(store.getState().config.pathPrefix),
}),
Expand Down Expand Up @@ -261,12 +266,7 @@ module.exports = async (
// optimizations for React) and whether prefixing links is enabled
// (__PREFIX_PATHS__) and what the link prefix is (__PATH_PREFIX__).
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(
process.env.NODE_ENV ? process.env.NODE_ENV : `production`
),
PUBLIC_DIR: JSON.stringify(`${process.cwd()}/public`),
},
"process.env": processEnv(stage, `production`),
__PREFIX_PATHS__: program.prefixPaths,
__PATH_PREFIX__: JSON.stringify(store.getState().config.pathPrefix),
}),
Expand Down