cross-env 和 dotenv 的使用

cross-env

A simple node program for executing commands using an environment from an env file.

npm install env-cmd

使用

  • 使用自定义的env文件
./node_modules/.bin/env-cmd -f ./custom/path/.env node index.js  // 后面是需要执行的脚本命令

help

  -v, --version                       output the version number
  -e, --environments [env1,env2,...]  The rc file environment(s) to use
  -f, --file [path]                   Custom env file path (default path: ./.env)
  --fallback                          Fallback to default env file path, if custom env file path not found
  --no-override                       Do not override existing environment variables
  -r, --rc-file [path]                Custom rc file path (default path: ./.env-cmdrc(|.js|.json)
  --silent                            Ignore any env-cmd errors and only fail on executed program failure.
  --use-shell                         Execute the command in a new shell with the given environment
  --verbose                           Print helpful debugging information
  -x, --expand-envs                   Replace $var in args and command with environment variables
  -h, --help                          output usage information

.rc 文件

对于更复杂的项目,可以在根目录中定义一个 .env-cmdrc 文件,并支持任意数量的环境。 只需使用 -e 标志并从 .env-cmdrc 文件中提供您希望使用的环境。 使用多个环境名称会将环境变量合并在一起。 如果发现冲突的环境变量,后面的环境会覆盖列表中的早期环境。

  • ./.env-cmdrc
{
  "development": {
    "ENV1": "Thanks",
    "ENV2": "For All"
  },
  "test": {
    "ENV1": "No Thanks",
    "ENV3": "!"
  },
  "production": {
    "ENV1": "The Fish"
  }
}
  • 使用命令
./node_modules/.bin/env-cmd -e production node index.js
# Or for multiple environments (where `production` vars override `test` vars, 
# but both are included) 
./node_modules/.bin/env-cmd -e test,production node index.js

dotenv

Dotenv 是一个零依赖模块,它将环境变量从 .env 文件加载到 process.env 中。 将配置与代码分开存储在环境中基于十二因素应用程序方法

npm install dotenv --save

使用

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

    HOST=localhost
    PORT=3000
    MONGOOSE_URL=mongodb://localhost:27017/test
    
  2. 在文件中引入配置信息

    require('dotenv').config({ path: '.env' })
    
    // 使用
    console.log(process.env.HOST) // localhost
    console.log(process.env.PORT) // 3000
    console.log(process.env.MONGOOSE_URL) // mongodb://localhost:27017/test
    
posted @   依梦维马  阅读(947)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示