访问环境变量时出现意外令牌

Unexpected token while access an env variable

我正在尝试在我的 nuxt 项目的 .env 文件中添加环境变量。

我的 Nuxt.js 版本是 2.15.3

这是我的 nuxt.config.js 的片段:

export default {
  publicRuntimeConfig: {
    baseURL: process.env.BASE_URL
  },
  ssr: false,
  target: 'static',
}

这是我的 .env 文件:

BASE_URL=https://my-url.smth

但是当我 运行 npm run dev 然后 nuxt 给出错误:

ERROR in ./.env 1:14 Module parse failed: Unexpected token (1:14) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

这篇文章指导了我 https://nuxtjs.org/tutorials/moving-from-nuxtjs-dotenv-to-runtime-config/

它也不适用于通过 @nuxtjs/dotenv 的旧方法。

编辑:解决方案是将变量用双引号括起来,像这样 BASE_URL="https://my-url.smth"


我已经写了一篇关于这个主题的 in-depth answer
如其中所述,请不要使用 @nuxtjs/dotenv 包。

如果您仍有问题,我们可能需要更多详细信息或至少 repro 才能更有效地帮助您。