Skip to content

Commit

Permalink
Merge pull request #5 from mrsteele/feature/dotenv-safe
Browse files Browse the repository at this point in the history
feat: Adding support for safe dotenv compilation.
  • Loading branch information
mrsteele authored Aug 6, 2016
2 parents 235f41a + 5d556de commit 96d7536
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 16 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ module.exports = {
...
plugins: [
new Dotenv({
path: './.env' // can be ommitted as this is the default
path: './.env', // can be ommitted as this is the default
safe: false, // make true to use dotenv-safe and require varialbes
sample: './.env.example', // if safe=true, use this to define the safe env
systemvars: false // if true, also loads system env variables
})
]
...
Expand Down
7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@
},
"keywords": [
"dotenv",
"env",
"safe",
"environment",
"dotenv-safe",
"variables",
"process",
"process.env",
"webpack",
"plugin"
],
Expand Down
45 changes: 30 additions & 15 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,41 @@
import { parse } from 'dotenv'
import dotenv from 'dotenv-safe'
import fs from 'fs'
import { DefinePlugin } from 'webpack'

class Dotenv {
constructor (options) {
options = options || {}
if (!options.path) options.path = './.env'
options = Object.assign({
path: './.env',
safe: false,
sample: './.env.example',
systemvars: true
}, options)

this.env = {}
try {
this.env = parse(fs.readFileSync(options.path))
} catch (err) {}
}
let vars = (options.systemvars) ? Object.assign({}, process.env) : {}
const blueprint = (options.safe) ? this.loadFile(options.sample) : this.loadFile(options.path)
const env = this.loadFile(options.path)

apply (compiler) {
const plugin = Object.keys(this.env).reduce((definitions, key) => {
const value = process.env[key] || this.env[key]
definitions[`process.env.${key}`] = JSON.stringify(value)
return definitions
}, {})
Object.keys(blueprint).map(key => {
const value = env[key] || env[key]
if (!value) {
throw new Error(`Missing environment variable: ${key}`)
} else {
vars[key] = value
}
})

compiler.apply(new DefinePlugin(plugin))
return new DefinePlugin({
'process.env': JSON.stringify(vars)
})
}

loadFile (file) {
try {
return dotenv.parse(fs.readFileSync(file))
} catch (err) {
console.warn(`Failed to load ${file}.`)
return {}
}
}
}

Expand Down

0 comments on commit 96d7536

Please sign in to comment.