.env和.env.[mode]和.env.[mode].local的优先级

3,574 阅读1分钟

对于vue-cli项目的环境变量配置文件,如果它们中有定义重名的变量,则取值优先级由高到低如下:

  1. .env.[mode].local 文件中的定义
  2. .env.[mode] 文件中的定义
  3. .env.local 文件中的定义
  4. .env 文件中的定义

简言之,有mode胜于无mode,具有相同mode或者同时没有mode,有local胜于无local

.env.local.env 是在所有环境都会被载入的。

此外,Vue CLI 启动时已经存在的环境变量拥有最高优先级,并不会被 .env 文件覆写。

.env 环境文件是通过运行 vue-cli-service 命令载入的,因此环境文件发生变化,你需要重启服务。

还需要注意的是,在 vue-cli项目中,除了NODE_ENVBASE_URL 和以 VUE_APP_ 开头的变量,其他的变量

定义并不会被webpack.DefinePlugin静态地插入到客户端代码中。

下面再附上一段dotenv解析env文件的规则,也是我们在写环境变量文件时要遵守的规则:

The parsing engine currently supports the following rules:

  • BASIC=basic becomes {BASIC: 'basic'}
  • empty lines are skipped
  • 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
{MULTILINE: 'new
line'}