Official website documentation: Environment variables-Ant Design Pro
- Pro scaffolding uses Umi as the underlying framework by default. In Umi, you can distinguish the configuration files of different environments
UMI_ENV
by specifying environment variables , which need to be configured within .UMI_ENV
package.json
- When
UMI_ENV
it istest
, you must configure files in the config directoryconfig.test.ts
to managetest
different variables in the environment. The Umi framework will form the final configuration after deep merge.- If you need to use this environment variable in an
config
external non-node environment file, you need to configure it whenconfig
exporting the default .defineConfig()
define{}
1. Add the UMI_ENV variable in the package.json file and assign a custom environment name.
Environment name: such as dev , test, pre, prod, etc. represent different domain names.
2. Create a new config.environment name.ts in the config directory under the project root directory.
Extension: If the config/config.ts file declares the same variable name as config/config.environment name.ts, the final value is read: the value in the config.environment name.ts file. -- Premise: In the command to run the project, the environment name of UMI_ENV is specified (that is, the first step above).
// config/config.dev.ts dev环境对应的配置文件
import { defineConfig } from 'umi';
/**
* 导出的多环境变量命名约定:一律大写且采用下划线分割单词
* 注意:在添加变量后,需要在src/typing.d.ts内添加该变量的声明,否则在使用变量时IDE会报错。
*/
export default defineConfig({
define: {
AGE: 18, // 年龄
'process.env': {
API_HOST_URL: "http://xxx_dev/xxx",
}
},
});
3. Run the commands in package.json and directly use environment variables in the .tsx page or .ts file.
Note: All .ts and other files in the config directory (node environment) cannot read the values of customized environment variables.
For example, if you run: npm run start:test , the environment variables declared in config.dev.ts will be automatically read.
// xxx.tsx
export default function addProject() {
console.log('dev环境', process.env.API_HOST_URL, AGE) // http://xxx_dev/xxx, 18
}
If you encounter a ts error (for example: the name "AGE" cannot be found), add the declaration of the relevant environment variables to the typings.d.ts file in the src directory under the project root directory:
declare const AGE: number;