工程配置类
dotenv
Dotenv是一个零依赖模块,它将环境变量从.env文件加载到process.env中。
官网地址
安装
# with npm
npm install dotenv
# or with Yarn
yarn add dotenv
在根目录创建一个.env文件,配置格式如下
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
文件规则
- BASIC=basic 变为 {BASIC: 'basic'}
- 空行会被跳过
- lines beginning with # are treated as comments
- empty values become empty strings (EMPTY= becomes {EMPTY: ''})
- inner quotes are maintained (think JSON) (JSON={"foo": "bar"} becomes {JSON:"{"foo": "bar"}")
- whitespace is removed from both ends of unquoted values (see more on trim) (FOO= some value becomes {FOO: 'some value'})
- single and double quoted values are escaped (SINGLE_QUOTE='quoted' becomes {SINGLE_QUOTE: "quoted"})
- single and double quoted values maintain whitespace from both ends (FOO=" some value " becomes {FOO: ' some value '})
- double quoted values expand new lines (MULTILINE="new\nline" becomes
使用
const dotenv = require('dotenv')
dotenv.config()
console.log(process.env.DB_HOST)
config 参数设置
设定需要转换的配置文件,默认是.env
dotenv.config({
path: path.resolve(process.cwd(), '.env.production'),
});
其它方法
parse 从其它来源获取的配置,通过Parse转换得到json, 例如通过fs.readFile读取,或者通过buffer
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
如果设置的变量与环境变量重复,环境变量将被保留(不会覆盖)
但有方法可以不这么做。使用文件读取,动态设置到process.env中
const fs = require('fs')
const dotenv = require('dotenv')
const envConfig = dotenv.parse(fs.readFileSync('.env.override'))
for (const k in envConfig) {
process.env[k] = envConfig[k]
}
网友评论