API 浏览器
Quasar CLI with Vite - @quasar/app-vite
处理 process.env

使用 process.env 可以在很多方面为你提供帮助:

¥Using process.env can help you in many ways:

  • 根据 Quasar 模式 (SPA/PWA/Cordova/Electron),区分运行时过程

    ¥differentiating runtime procedure depending on Quasar Mode (SPA/PWA/Cordova/Electron)

  • 根据运行的是开发版本还是生产版本,区分运行时过程

    ¥differentiating runtime procedure depending if running a dev or production build

  • 在构建时根据终端环境变量添加标志

    ¥adding flags to it based on terminal environment variables at build time

Quasar CLI 提供的值(Values provided by Quasar CLI)

¥Values provided by Quasar CLI

process∙env∙<name>类型含义
DEV布尔值代码在开发模式下运行
PROD布尔值代码在生产模式下运行
DEBUGGING布尔值代码在开发模式下运行,或已将 --debug 标志设置为生产模式
CLIENT布尔值代码在客户端运行(而非服务器端)
SERVER布尔值代码在服务器端运行(而非客户端)
MODE字符串Quasar CLI 模式(spapwa 等)
NODE_ENV字符串有两个可能的值:productiondevelopment
TARGET字符串对于 Cordova/Capacitor 模式,可以是 iosandroid;对于 BEX 模式,可以是 chromefirefox

示例(Example)

¥Example

if (process.env.DEV) {
  console.log(`I'm on a development build`)
}

// process∙env∙MODE is the <mode> in
// "quasar dev/build -m <mode>"
// (defaults to 'spa' if -m parameter is not specified)

if (process.env.MODE === 'electron') {
  import('@electron/remote').then(({ BrowserWindow }) => {
    const win = BrowserWindow.getFocusedWindow()

    if (win.isMaximized()) {
      win.unmaximize()
    }
    else {
      win.maximize()
    }
  })
}

剥离代码(Stripping out code)

¥Stripping out code

编译你的网站/应用时,会根据 process.env 评估 if () 分支,如果表达式为 false,则会将其从文件中删除。示例:

¥When compiling your website/app, if () branches depending on process.env are evaluated, and if the expression is false, they get stripped out of the file. Example:

if (process.env.DEV) {
  console.log('dev')
}
else {
  console.log('build')
}

// running with "quasar dev" will result in:
console.log('dev')
// while running with "quasar build" will result in:
console.log('build')

请注意,上文中 if 在编译时被评估并完全删除,从而导致包更小。

¥Notice above that the ifs are evaluated and also completely stripped out at compile-time, resulting in a smaller bundle.

基于 process.env 导入(Import based on process.env)

¥Import based on process.env

你可以将上一节中学到的知识与动态导入结合使用:

¥You can combine what you learned in the section above with dynamic imports:

if (process.env.MODE === 'electron') {
  import('my-fancy-npm-package').then(package => {
    // notice "default" below, which is the prop with which
    // you can access what your npm imported package exports
    package.default.doSomething()
  })
}

添加到 process.env(Adding to process.env)

¥Adding to process.env

你可以通过 /quasar.config 文件向 process.env 添加你自己的定义。

¥You can add your own definitions to process.env through the /quasar.config file.

了解不同类型的环境变量非常重要。

¥It’s important to understand the different types of environment variables.

  • /quasar.config 文件中定义的来自终端的环境变量

    ¥The env variables from the terminal that are defined in the /quasar.config file

  • 传递给 UI 代码的环境变量

    ¥The environment variables that you pass to your UI code

/quasar.config file

// Accessing terminal variables
console.log(process.env)

export default defineConfig((ctx) => {
  return {
    // ...

    build: {
      // passing down to UI code from the quasar.config file
      env: {
        API: ctx.dev
          ? 'https://dev.api.com'
          : 'https://prod.api.com'
      }
    }
  }
})

然后,在你的网站/应用中,你可以访问 process∙env∙API,它将指向上述两个链接之一,具体取决于开发或生产构建类型。

¥Then, in your website/app, you can access process∙env∙API, and it will point to one of those two links above, depending on dev or production build type.

你甚至可以将它与 quasar dev/build 环境变量中的值结合使用:

¥You can even combine it with values from the quasar dev/build env variables:

# we set an env variable in terminal
$ MY_API=api.com quasar build
/quasar.config file

// then we pick it up in the /quasar.config file
build: {
  env: {
    API: ctx.dev
      ? 'https://dev.' + process.env.MY_API
      : 'https://prod.' + process.env.MY_API
  }
}

环境点文件支持(The env dotfiles support)

¥The env dotfiles support

稍微扩展了环境点文件的支持。这些文件将被检测和使用(顺序很重要):

¥Expanding a bit on the env dotfiles support. These files will be detected and used (the order matters):

.env                                # loaded in all cases
.env.local                          # loaded in all cases, ignored by git
.env.[dev|prod]                     # loaded for dev or prod only
.env.local.[dev|prod]               # loaded for dev or prod only, ignored by git
.env.[quasarMode]                   # loaded for specific Quasar CLI mode only
.env.local.[quasarMode]             # loaded for specific Quasar CLI mode only, ignored by git
.env.[dev|prod].[quasarMode]        # loaded for specific Quasar CLI mode and dev|prod only
.env.local.[dev|prod].[quasarMode]  # loaded for specific Quasar CLI mode and dev|prod only, ignored by git

…其中 “被 git 忽略” 假定在发布此包后创建了一个默认项目文件夹,否则,请将 .env.local* 添加到你的 /.gitignore 文件中。

¥…where “ignored by git” assumes a default project folder created after releasing this package, otherwise add .env.local* to your /.gitignore file.

你还可以配置从其他文件夹中获取上述文件,甚至可以将更多文件添加到列表中:

¥You can also configure the files above to be picked up from a different folder or even add more files to the list:

/quasar.config file

build: {
  /**

   * Folder where Quasar CLI should look for .env* files.

   * Can be an absolute path or a relative path to project root directory.

   *    * @default project root directory
   */
  envFolder?: string;

  /**

   * Additional .env* files to be loaded.

   * Each entry can be an absolute path or a relative path to quasar.config > build > envFolder.

   *    * @example ['.env.somefile', '../.env.someotherfile']
   */
  envFiles?: string[];

  /**

   * Filter the env variables that are exposed to the client

   * through the env files. This does not account also for the definitions

   * assigned directly to quasar.config > build > env prop.

   *    * Requires @quasar/app-vite v2.0.3+
   */
  envFilter?:
    (env: { [index: string]: string | boolean | undefined | null })
      => { [index: string]: string | boolean | undefined | null };
}

请记住,你可以使用 build > envFilter 过滤掉不需要的键,甚至可以更改键的值:

¥Remember that you can filter out unwanted keys, or even change values for keys by using build > envFilter:

/quasar.config file

build: {
  // @quasar/app-vite v2.0.3+
  envFilter (originalEnv) {
    const newEnv = {}
    for (const key in originalEnv) {
      if (/* ...decide if it goes in or not... */) {
        newEnv[ key ] = originalEnv[ key ]
      }
    }

    // remember to return your processed env
    return newEnv
  }
}

故障排除(Troubleshooting)

¥Troubleshooting

如果你错误地访问了变量或配置有误,你可能会在浏览器控制台中收到 process is not defined 错误。

¥You might be getting process is not defined errors in the browser console if you are accessing the variables wrong or if you have a misconfiguration.

错误用法(Wrong usage)

¥Wrong usage

/quasar.config file

build: {
  env: {
    FOO: 'hello',
  }
}
const { FOO } = process.env // ❌ It doesn't allow destructuring or similar
process.env.FOO             // ✅ It can only replace direct usage like this

function getEnv(name) {
  return process.env[name] // ❌ It can't analyze dynamic usage
}

console.log(process)     // ❌
console.log(process.env) // ❌
// If you want to see a list of available env variables,
// you can log the object you are passing to `build > env` inside the `quasar.config` file

console.log(process.env.FOO) // ✅
console.log(process.env.foo) // ❌ Case sensitive
console.log(process.env.F0O) // ❌ Typo in the variable name (middle o is 0(zero))

配置错误(Misconfiguration)

¥Misconfiguration

手动定义(Manual definition)

¥Manual definition

/quasar.config file

build: {
  env: {
    FOO: 'hello',
  }
}
console.log(process.env.FOO) // ✅
console.log(process.env.BAR) // ❌ It's not defined in `build > env`

环境点文件(The env dotfiles)

¥The env dotfiles

# order matters!
.env                                # loaded in all cases
.env.local                          # loaded in all cases, ignored by git
.env.[dev|prod]                     # loaded for dev or prod only
.env.local.[dev|prod]               # loaded for dev or prod only, ignored by git
.env.[quasarMode]                   # loaded for specific Quasar CLI mode only
.env.local.[quasarMode]             # loaded for specific Quasar CLI mode only, ignored by git
.env.[dev|prod].[quasarMode]        # loaded for specific Quasar CLI mode and dev|prod only
.env.local.[dev|prod].[quasarMode]  # loaded for specific Quasar CLI mode and dev|prod only, ignored by git

如果 /.env 不存在或文件名有拼写错误:

¥If the /.env doesn’t exist or there is a typo in the file name:

console.log(process.env.FOO) // ❌ The .env file is not loaded, this will fail

如果 /.env 文件存在且名称正确,并且包含以下内容:

¥If the /.env file exists with the correct name, and has the following content:

/.env

FOO=hello
console.log(process.env.FOO) // ✅ It's loaded correctly from the `.env` file
console.log(process.env.BAR) // ❌ It's not defined in the `.env` file