访问 process.env
可以在很多方面为你提供帮助:
¥Accessing 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 supplied by Quasar CLI)
¥Values supplied by Quasar CLI
process∙env∙<name> | 类型 | 含义 |
---|---|---|
DEV | 布尔值 | 代码在开发模式下运行 |
PROD | 布尔值 | 代码在生产模式下运行 |
DEBUGGING | 布尔值 | 代码在开发模式下运行,或已将 --debug 标志设置为生产模式 |
CLIENT | 布尔值 | 代码在客户端运行(而非服务器端) |
SERVER | 布尔值 | 代码在服务器端运行(而非客户端) |
MODE | 字符串 | Quasar CLI 模式(spa 、pwa 等) |
NODE_ENV | 字符串 | 有两个可能的值:production 或 development |
TARGET | 字符串 | 对于 Cordova/Capacitor 模式,可以是 ios 或 android ;对于 BEX 模式,可以是 chrome 或 firefox 。 |
示例(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') {
const { BrowserWindow } = require('@electron/remote')
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
then 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 if
s 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.
首先,这里有两个概念需要理解。终端中 /quasar.config
文件本身可用的环境变量,以及你传递给 UI 代码的环境变量。
¥But first, there’s two concepts that need to be understood here. The env variables from the terminal that are available in the /quasar.config
file itself and the environment variables that you pass to your UI code.
// 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’s gonna point to one of those two links above, based on dev or production build type.
你甚至可以更进一步。为其提供从 quasar dev/build
环境变量中获取的值:
¥You can even go one step further. Supply it with values taken from the quasar dev/build
env variables:
# we set an env variable in terminal
$ MY_API=api.com quasar build
// 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:
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-webpack v4.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
:
build: {
// @quasar/app-webpack v4.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
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
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:
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