话不多说,让我们开始服务吧! ! !
获取第一手代码:
git clone https://github.com/motdotla/dotenv.git
# npm i -g yarn
cd dotenv && yarn i
作用是将.env文件中的变量放入.env中
接下来我们看一下我们常用的.env文件,大概猜猜它们做了什么
// .env
NODE_ENV=development
URL='http://xxx.cn'
首先获取文件内容并解析文件内容(类似key=value)并将解析内容遍历到.env中
看一下源码:
const fs = require('fs')
const path = require('path')
const os = require('os')
function log (message ) {
console.log(`[dotenv][DEBUG] ${message}`)
}
const newline = '\n'
const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/
const RE_newlineS = /\\n/g
const newlineS_MATCH = /\r\n|\n|\r/
// Parses src into an Object
function parse (src , options ) {
const debug = Boolean(options && options.debug)
const obj = {}
// convert Buffers before splitting into lines and processing
src.toString().split(newlineS_MATCH).forEach(function (line, idx) {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(RE_INI_KEY_VAL)
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1]
// default undefined or missing values to empty string
let val = (keyValueArr[2] || '')
const end = val.length - 1
const isDoubleQuoted = val[0] === '"' && val[end] === '"'
const isSingleQuoted = val[0] === "'" && val[end] === "'"
// if single or double quoted, remove quotes
if (isSingleQuoted || isDoubleQuoted) {
val = val.substring(1, end)
// if double quoted, expand newlines
if (isDoubleQuoted) {
val = val.replace(RE_newlineS, newline)
}
} else {
// remove surrounding whitespace
val = val.trim()
}
obj[key] = val
} else if (debug) {
log(`did not match key and value when parsing line ${idx + 1}: ${line}`)
}
})
return obj
}
function resolveHome (envPath) {
return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
}
// Populates process.env from .env file
function config (options ) {
let dotenvPath = path.resolve(process.cwd(), '.env')
let encoding = 'utf8'
let debug = false
if (options) {
if (options.path != null) {
dotenvPath = resolveHome(options.path)
}
if (options.encoding != null) {
encoding = options.encoding
}
if (options.debug != null) {
debug = true
}
}
try {
// specifying an encoding returns a string instead of a buffer
const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug })
Object.keys(parsed).forEach(function (key) {
if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
process.env[key] = parsed[key]
} else if (debug) {
log(`"${key}" is already defined in \`process.env\` and will not be overwritten`)
}
})
return { parsed }
} catch (e) {
return { error: e }
}
}
module.exports.config = config
module.exports.parse = parse
代码比较长,主要看方法。 大概意思是它正在处理获取到的文件内容,并将其转换为对象
方法是获取文件内容,遍历并将方法的对象赋值给.env,并返回该对象
都到这里了,那么浏览器是如何访问环境变量的呢? .env 仅在节点环境中。 这时候就需要做一些操作,把构建时的环境变量保存到另外一个地方。
是的,——两人也做过类似的事情。 具体实现思路是在构建时复制.env的内容,这样方便区分,直接使用'.env.xxx'作为key来赋值对应的值
有兴趣的话可以看看源码,是结合和开发的