vite.confg.js npm run xxx和.env文件详解
在vite.config.js中: export default defineConfig(({ mode, command }) => { /** *参数: (1)mode: 就是运行npm run xxx的时候的模式,配置项"--mode"后面的字符串将被传入到defineConfig函数中
其中:.env文件是必读的,后面的.env.xxx会覆盖掉.env文件内容。变量名必须以"VITE_"开头
比如package.json中的脚本
"scripts": {
//npm run serve启动后默认读取.env.development文件,并将环境变量注入到import.meta.env中
//npm run build启动后默认读取.env.production文件,并将环境变量注入到import.meta.env中
//npm run build:stage启动后根据"--mode"后面的字符串读取.env.staging文件,并将环境变量注入到import.meta.env中
"serve": "vite", //相当于运行了 npm run serve --mode development,因为vite的默认环境就是development,所以可以省略"--mode development"
"build:prod": "vite build", //相当于运行了 npm run serve --mode build
"build:stage": "vite build --mode staging",
(2)command: "build" | "serve"*
*/
//process.cwd() 返回node进程的工作目录,如:G:\program_demo\vueProgram\RuoYi-Vue-master\RuoYi-Vue3
const env = loadEnv(mode, process.cwd()) //获取环境变量
console.log("process.cwd():",process.cwd());
console.log("env:",env);
const { VITE_APP_ENV } = env
return {
// 部署生产环境和开发环境下的URL。
// 默认情况下,vite 会假设你的应用是被部署在一个域名的根路径上
// 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.ruoyi.vip/admin/,则设置 baseUrl 为 /admin/。
base: VITE_APP_ENV === 'production' ? '/' : '/',
plugins: createVitePlugins(env, command === 'build'),
resolve: {
// https://cn.vitejs.dev/config/#resolve-alias
alias: {
// 设置路径
'~': path.resolve(__dirname, './'),
// 设置别名
'@': path.resolve(__dirname, './src')
},
// https://cn.vitejs.dev/config/#resolve-extensions
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
},
// vite 相关配置
}
})