如何在 nuxt 中为 dotenv 设置自定义路径

How to set custom path for dotenv in nuxt

我有以下 nuxt.config.js,其中 srcDir 指向“主应用程序”,我将 .env 放在它外面。那么在nuxt.config.js中,如何在第1行设置自定义路径

require('dotenv').config({ path: '../.env' })

这样我的 process.env 就可以工作了

还有nuxt.config.js中的buildModules如下

buildModules: ["@nuxtjs/fontawesome", "@nuxtjs/dotenv"],

你试过吗?

const { resolve } = require('path')
require('dotenv').config({ path: resolve(__dirname,"../.env") })

摘自 this answer.


不然这个题好像也有很多解法:


编辑: 你可以把它写在 nuxt.config.js 文件的顶部,在 export default 的范围之外。

const { resolve } = require('path')
const current = resolve(__dirname)
const upper = resolve(__dirname, '..')
console.log('current', current)
console.log('upper', upper)

const testFolder = '../'

fs.readdir(testFolder, (_err, files) => {
  files.forEach((file) => {
    console.log(file)
  })
})

export default {
  publicRuntimeConfig: {
  // rest of the nuxt.config.js file below

在我的 Linux 机器上提供这个。

实际上我需要像下面这样在buildModules部分设置env的实时路径

 buildModules: ["@nuxtjs/fontawesome", ['@nuxtjs/dotenv', { path: './' }]],

如果您使用的版本 > 2.13,那么您将不再需要安装 dotenv,因为它已经内置 https://nuxtjs.org/docs/directory-structure/nuxt-config/#runtimeconfig

.env support Similar to vue-cli (*), .env file will be always loaded via dotenv and is accessible via process.env and options._env. process.env is updated so one can use it right inside nuxt.config for runtime config. Values are interpolated and expanded with an improved version of dotenv-expand. .env file is also watched to reload during nuxt dev. Path can be set via cli --dotenv or disabled by --dotenv false.

我创建了 .env.xxx 文件并创建了相应的脚本