了解下环境变量在vite中

  • 官方文档说到.env.[mode] # 只在指定模式下加载,比如.env.development只在开发环境加载

  • 至于为什么是development,而不是其他的,因为默认就是developmentproduction来区分开发和生产

    • 你也可以自定义,只需要在启动的时候添加--mode xxxx就可以,比如下面的

    • 下图为输出查看import.meta.env,就会发现mode变为了abdfed

“import.meta” is not available with the “cjs” output format and will be empty [empty-import-meta]

  • 如果你在vite.config.js中直接使用import.meta.env,就会发现出现这个错误了
1
2
3
4
5
6
7
正在编译中...
▲ [WARNING] "import.meta" is not available with the "cjs" output format and will be empty [empty-import-meta]

vite.config.js:15:28:
15target: import.meta.env.VITE_APP_BASE_API,
╵ ~~~~~~~~~~~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { defineConfig,loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'

export default defineConfig(({ mode }) => {
const root = process.cwd();
const viteEnv = loadEnv(mode, root);
console.log(viteEnv.VITE_API_ADDRESS);
return {
base: './',
build: {
minify: true,
outDir: 'dist',
},
server: {
port: '8067',
proxy: {
"^/sys": {
target: "https://abc.com",
changeOrigin: true,
},
},
},
plugins: [
uni()
],
exclude:[
/\/README\.md$/,
]
}
})