1.0.4 • Published 7 years ago
env-to-code v1.0.4
env-to-code
The module to parse process.env[SOME_KEY] into JavaScript variable or JavaScript code, especially, which is very useful for webpack.EnvironmentPlugin
Install
$ npm i env-to-codeUsage
# bash
export FOO=bar
export BAZ=1
export DEBUG=falseimport {
js,
code
} from 'env-to-code'
js(process.env.FOO) === 'bar' // true
code(process.env.FOO) === '"bar"' // true
js(process.env.BAZ) === 1 // true
js(process.env.DEBUG) === false // true
code(process.env.DEBUG) === 'false' // true
// But
JSON.stringify(process.env.DEBUG) === '"false"' // true
new webpack.DefinePlugin({
'process.env.DEBUG': code(process.env.DEBUG)
})js(s, config?)
- s
stringenvironment variable string - config
?Objectoptional config- testJSON
?boolean=falsewhether to test ifsis a JSON.testJSONtakes effect ahead ofarrayDelimiter. - arrayDelimiter
?string=','by default, it will try to split the env variable into array witharrayDelimiter. To disable this feature, set the option tofalseor''
- testJSON
Parses the environment variable into JavaScript variable.
js('English, Chinese') // ['English', 'Chinese']
js('English') // 'English'
js('English, Chinese', {
arrayDelimiter: false
})
// 'English, Chinese'PAY ATTENTION THAT with testJSON=false and arrayDelimiter=',' which are the default options, method js() will split JSON array into an unexpected result, for example:
js('["a","b"]')
// [
// '["a"',
// '"b"]'
// ]So, if environment variables contains JSON strings, it is better to set testJSON to true:
js('["a","b"]', {testJSON: true})
// ['a', 'b']code(s, config?)
This method has the same arguments as js(), and parses s into JavaScript code string.
So it is useful for webpack.EnvironmentPlugin or writing JavaScript code into files.
new webpack.DefinePlugin({
'process.env.NODE_ENV': code(process.env.NODE_ENV),
'process.env.DEBUG': code(process.env.DEBUG)
})or
// write.js
fs.writeFileSync('foo.js', `module.exports = {debug:${code(process.env.DEBUG)}}`)DEBUG=true node write.jsAnd in foo.js
module.exports = {debug:true}License
MIT