envdot

使用 envdot 管理node项目的环境相关变量,.env 文件中的变量会放入process.env

和webpack整合使用

  1. 使用npm/yarn 安装 dotenv 和 dotenv-expand
  1. npm install dotenv dotenv-expand --save-dev
  1. 新建env.js文件 ```javascript “use strict”;

const fs = require(“fs”); const path = require(“path”);

// NODE_ENV根据env文件传入 const NODE_ENV = process.env.NODE_ENV; if (!NODE_ENV) { throw new Error( “The NODE_ENV environment variable is required but was not specified.” ); }

// Make sure any symlinks in the project folder are resolved: // https://github.com/facebook/create-react-app/issues/637 const appDirectory = fs.realpathSync(process.cwd()); const resolveApp = relativePath => path.resolve(appDirectory, relativePath); const dotenv = resolveApp(“.env”);

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use var dotenvFiles = [ ${dotenv}.${NODE_ENV}.local, ${dotenv}.${NODE_ENV}, // Don’t include .env.local for test environment // since normally you expect tests to produce the same // results for everyone NODE_ENV !== “test” && ${dotenv}.local, dotenv ].filter(Boolean);

// Load environment variables from .env* files. Suppress warnings using silent // if this file is missing. dotenv will never modify any environment variables // that have already been set. Variable expansion is supported in .env files. // https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv-expand dotenvFiles.forEach(dotenvFile => { if (fs.existsSync(dotenvFile)) { require(“dotenv-expand”)( require(“dotenv”).config({ path: dotenvFile }) ); } });

const REACTAPP = /^REACT_APP/i;

function getClientEnvironment() { const raw = Object.keys(process.env) .filter(key => REACT_APP.test(key)) .reduce( (env, key) => { env[key] = process.env[key]; return env; }, { // Useful for determining whether we’re running in production mode. // Most importantly, it switches React into the correct mode. JS_ENV: process.env.JS_ENV || “development” } ); // Stringify all values so we can feed into Webpack DefinePlugin const stringified = { “process.env”: Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; }, {}) };

return { raw, stringified }; }

module.exports = getClientEnvironment;

  1. 3. webpack配置文件中引入此文件
  2. ```javascript
  3. // Ensure environment variables are read.
  4. const getClientEnvironment = require("./config/env");
  5. const env = getClientEnvironment();
  6. // plugins:
  7. new webpack.DefinePlugin(env.stringified)
  1. 在项目根目录下新建.env文件,文件内容格式参考: https://github.com/motdotla/dotenv
    1. # 保存所有环境公共的环境变量,process.env
    2. AAA=123

可以创建多个.env文件,构建时根据 NODE_ENV 进行区分: dev, test, prod
配置文件优先级如下,如果多个配置文件有重名变量,最后取值为优先级高的文件中的值:

  1. .env.dev.local > .env.local > .env.dev > .env
  2. .env.test.local > .env.local > .env.test > .env
  3. .env.prod.local > .env.local > .env.prod > .env

参考

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
creact-react-app
上面env.js的代码来源于creact-react-app生成的项目,运行npm eject后的config/env.js