vite 构建 不同环境
2024-02-05 本文已影响0人
前端早晚自习
之前项目大部分把打包配置揉在一个文件, dev、预发布、生成环境都共用一个配置,或根据变量判断, 这几个一直在优化项目通过 mergeConfig 合并不同的配置
目录结构
image.png基础配置
import { resolve } from 'path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import svgLoader from 'vite-svg-loader';
export default defineConfig({
plugins: [vue(), vueJsx(), svgLoader({ svgoConfig: {} })],
resolve: {
alias: [
{
find: '@',
replacement: resolve(__dirname, '../src'),
},
{
find: 'assets',
replacement: resolve(__dirname, '../src/assets'),
},
{
find: 'vue',
replacement: 'vue/dist/vue.esm-bundler.js', // compile template
},
],
extensions: ['.ts', '.js'],
},
define: {
'process.env': {},
},
css: {
preprocessorOptions: {
less: {
modifyVars: {
hack: `true; @import (reference) "${resolve(
'src/assets/style/breakpoint.less'
)}";`,
},
javascriptEnabled: true,
},
},
},
});
生产环境和dev 环境
dev
import { mergeConfig } from 'vite';
import eslint from 'vite-plugin-eslint';
import baseConfig from './vite.config.base';
import createSvgIcon from './plugin/svg-icon';
export default mergeConfig(
{
mode: 'development',
server: {
open: true,
},
plugins: [
eslint({
cache: false,
include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.vue'],
exclude: ['node_modules'],
}),
createSvgIcon(false),
],
},
baseConfig
);
生产
import { mergeConfig } from 'vite';
import baseConfig from './vite.config.base';
import configCompressPlugin from './plugin/compress';
import configVisualizerPlugin from './plugin/visualizer';
import configArcoResolverPlugin from './plugin/arcoResolver';
import configStyleImportPlugin from './plugin/styleImport';
import configImageminPlugin from './plugin/imagemin';
import createSvgIcon from './plugin/svg-icon';
export default mergeConfig(
{
mode: 'production',
plugins: [
configCompressPlugin('gzip'),
configVisualizerPlugin(),
configArcoResolverPlugin(),
configStyleImportPlugin(),
configImageminPlugin(),
createSvgIcon(true),
],
build: {
rollupOptions: {
output: {
manualChunks: {
arco: ['@arco-design/web-vue'],
chart: ['echarts', 'vue-echarts'],
vue: ['vue', 'vue-router', 'pinia', '@vueuse/core', 'vue-i18n'],
},
},
},
chunkSizeWarningLimit: 2000,
},
},
baseConfig
);
package.json
"scripts": {
"dev": "vite --config ./config/vite.config.dev.ts",
"build": "vue-tsc --noEmit && vite build --config ./config/vite.config.prod.ts",
"report": "cross-env REPORT=true npm run build",
"preview": "npm run build && vite preview --host",
},
最后
这种代码组织方式结构清晰, 做到了低耦合, 可扩展性也高。。本文主要是让自己,通过某个功能对自己代码进行review和重实现来提高代码质量,希望各位大佬多多指点