[Vue3] vite obtains the environment variables configured in the .env file

1. Modify vite.config.ts configuration

Main configuration

// 根据当前工作目录中的 `mode` 加载 .env 文件
// 第二个参数:process.cwd()表示返回运行当前脚本的工作目录的路径(current work directory)
// 设置第三个参数为 '' 来加载所有环境变量,而不管是否有 `VITE_` 前缀。
const env = loadEnv(mode.mode, process.cwd(), '');

vite.config.tsThe file is in the root directory of the project, the specific configuration is as follows

import vue from '@vitejs/plugin-vue';
import {
    
     resolve } from 'path';
import {
    
     defineConfig, loadEnv, ConfigEnv } from 'vite';
import vueSetupExtend from 'vite-plugin-vue-setup-extend-plus'; // setup的name语法插件

const pathResolve = (dir: string): any => {
    
    
	return resolve(__dirname, '.', dir);
};

const alias: Record<string, string> = {
    
    
	'/@': pathResolve('./src/'),
	'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
};

const viteConfig = defineConfig((mode: ConfigEnv) => {
    
    
//检查process.cwd()路径下.env.development.local、.env.development、.env.local、.env这四个环境文件
	const env = loadEnv(mode.mode, process.cwd());
	return {
    
    
		plugins: [vue(), vueSetupExtend()],
		root: process.cwd(),
		resolve: {
    
     alias },
		base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
		hmr: true,
		optimizeDeps: {
    
    
			include: ['element-plus/lib/locale/lang/zh-cn', 'element-plus/lib/locale/lang/en', 'element-plus/lib/locale/lang/zh-tw'],
		},
		server: {
    
    
			host: '0.0.0.0',
			port: env.VITE_PORT as unknown as number,
			open: env.VITE_OPEN,
			proxy: {
    
    
				'/gitee': {
    
    
					target: 'https://gitee.com',
					ws: true,
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/gitee/, ''),
				},
			},
		},
		build: {
    
    
			outDir: 'dist',
			sourcemap: false,
			chunkSizeWarningLimit: 1500,
			rollupOptions: {
    
    
				output: {
    
    
					entryFileNames: `assets/[name].${
      
      new Date().getTime()}.js`,
					chunkFileNames: `assets/[name].${
      
      new Date().getTime()}.js`,
					assetFileNames: `assets/[name].${
      
      new Date().getTime()}.[ext]`,
					compact: true,
					manualChunks: {
    
    
						vue: ['vue', 'vue-router', 'pinia'],
						echarts: ['echarts'],
					},
				},
			},
		},
		css: {
    
     preprocessorOptions: {
    
     css: {
    
     charset: false } } },
		define: {
    
    
			__VUE_I18N_LEGACY_API__: JSON.stringify(false),
			__VUE_I18N_FULL_INSTALL__: JSON.stringify(false),
			__INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
		},
	};
});

export default viteConfig;

2. Configure the configuration parameters in the .env file

insert image description here
Vite official website configuration reference

.env                # 所有情况下都会加载
.env.local          # 所有情况下都会加载,但会被 git 忽略
.env.[mode]         # 只在指定模式下加载
.env.[mode].local   # 只在指定模式下加载,但会被 git 忽略
# 路径变量必须得用VITE_开头, 修改后需要重启
VITE_BASE_URL = 'http://localhost:8888/'

3. Obtain parameters in js

console.log(import.meta.env.VITE_BASE_URL);

Guess you like

Origin blog.csdn.net/weixin_42960907/article/details/126929386