一、先下载库:babel-plugin-transform-inline-environment-variables
npm install babel-plugin-transform-inline-environment-variables --save-dev
二、配置项目根目录下的.babelrc文件
{
"plugins": [
"transform-inline-environment-variables"
]
}
三、在config/dev.js(开发环境)文件中配置常量defineConstants字段
注意:
1. 每次修改该配置文件后,都需要手动再 重新运行编译命令, 否则常量不能使用!!!
2. 在 defineConstants字段中:定义的常量,除了Number类型,其他类型(如:字符串、对象等)的值,都需要 先转成json形式存储,但是在页面或xx.js文件中使用时,不用再JSON.parse()转换, 直接就是普通的字符、对象类型,可以直接使用。
const userObj = { name: '小兰',age: 19 }
module.exports = {
env: {
NODE_ENV: '"development"',
},
defineConstants: {
NAME: '"小明"',
AGE: 18,
HOST_NAME: '"http://www.baodu.com"', // 注意:非Number类型的值,必须要写成json字符。
USER_INFO: JSON.stringify(userObj)
},
mini: {},
h5: {
devServer: {
proxy: {
'/wxWork/': {
target: 'https://qyapi.weixin.qq.com/',
pathRewrite: {
'^/wxWork/': '',
},
changeOrigin: true,
},
'/crm/': {
target: 'http://xxxx.com/',
pathRewrite: {
'^/crm/': '',
},
changeOrigin: true,
},
},
},
},
}
四、在xx.tsx页面中使用常量(直接在代码中写常量名即可-类似全局变量)
注意:先运行(开发环境)编译命令:npm run dev:h5
class App extends Component<PropsWithChildren> {
componentDidMount() {
console.log('当前运行环境是', process.env.NODE_ENV, NAME, HOST_URL, USER_INFO.name) // development, '小明', 'http://www.baodu.com', '小兰'
}
}
或在xxx.ts中使用
console.log(HOST_URL) // 'http://www.baodu.com'