07-dotenv环境插件

644 阅读1分钟

环境配置 dotenv

dotenv

dotenv本来是为服务端CommonJS服务,为node配置环境变量文件 .env,进而将 .env 的变量 挂载到 process.env上。但是现在我们希望直接的将它集成在webpack上。为啥?

webpack.DefinePlugin明明已经提供了定义环境变量的配置,不过不得不说的是,它并不提供自动的读取 .env 的功能,并且 webpack.DefinePlugin 只是为源文件提供的了 process.env.xxx 的替换功能,并未真正的 为node的process.env挂载变量

dotenv 怎么使用

  1. 在根目录下创建.env文件

    DB_HOST=localhost
    DB_USER=root
    DB_PASS=s1mpl3
    
  2. 通过 dotenv 加载

    // index.js
    const result = dotenv.config() // 自动加载 .env文件生成对象
    console.log(result.error, result.parsed) 
    console.log(process.env.DB_PASS)
    

dotenv.config做了什么?

  • 读取文件.env,将它组合成对象,保存在 result.parsed
  • 如果读取失败 result.error
  • 将读取的对象键值对赋值给 process.env

dotenv-extend

dotenv-extend dotenv-extend 是 对 dotenv的拓展(插件),它能够将 dotenv.config生成的对象解析一遍:

  • $KEY will expand any env with the name KEY
  • ${KEY} will expand any env with the name KEY
  • $KEY will escape the $KEY rather than expand
  • ${KEY:-default} will first attempt to expand any env with the name KEY. If not one, then it will return default

dotenv-webpack 插件

dotenv-webpack

直接为你加载env文件

const Dotenv = require('dotenv-webpack')
let plugins = [
  ...plugins,
  new Dotenv()
]

dotenv 和 define-plugin配合使用

dotenv + define-plugin

高可配置的自定义环境变量文件:

const dotenv = require('dotenv')

const env = dotenv.config().parsed
const envKeys = Object.keys(env).reduce((prev, next) => {
  prev[`process.env.${next}`] = JSON.stringify(env[next])
  return prev
}, {});

const plugins = [
  new webpack.DefinePlugin(envKeys)
]

总结

将dotenv一方面是挺好用的,另外是create-react-app使用到了它,接下里会分析脚手架的具体配置。