1.根据不同环境变量打包 lib
1.package.json 中配置打包脚本
"scripts": {
"dev": "vite",
"serve": "vite",
"build": "vite build",
"lib": "vite build --mode lib",
}
2.vite.config.js 配置环境变量的用法
// vite.config.js
import { defineConfig, loadEnv } from 'vite'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
console.log({ command, mode })
const env = loadEnv(mode, process.cwd(), '')
if (command === 'build' && mode === 'lib') {
return {
build: {
assetsDir: env.VITE_LIB_ASSETSDIR,
outDir: env.VITE_LIB_OUTDIR,
lib: {
entry: path.resolve(__dirname, env.VITE_LIB_ENTRY),
name: VITE_LIB_NAME,
// the proper extensions will be added
fileName: VITE_LIB_NAME
}
}
}
}
return defaultOptions
})
3.项目根目录添加环境变量配置文件.env.lib
// .env.lib
VITE_LIB_ASSETSDIR = lib / static
VITE_LIB_ENTRY = packages / index.js
VITE_LIB_OUTDIR = lib
VITE_LIB_NAME = lib - test
4.执行打包命令
npm run bulid --mode lib
5.分包策略配置 5.1使用output.manualChunks
// vite.config.js
import { defineConfig } from 'vite'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig(({ command, mode}) => {
return {
build: {
outDir: 'dist',
rollupOptions: {
output: {
manualChunks: {
'element': ['element-plus']
}
}
}
},
}
})
5.2使用vite-plugin-chunk-split
插件
import { defineConfig, loadEnv } from 'vite'
import { chunkSplitPlugin } from 'vite-plugin-chunk-split'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
...
chunkSplitPlugin({
// 指定拆包策略
customSplitting: {
element: ['element-plus']
}
})
],
})
2.同一项目配置不同入口
// vite.config.js
import { defineConfig } from 'vite'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig(({ command, mode}) => {
return {
build: {
outDir: 'dist',
rollupOptions: {
input: {
index: path.resolve(__dirname, 'index.html')
about: path.resolve(__dirname, 'about.html'),
},
output: {
chunkFileNames: 'js/[name]-[hash].js',
entryFileNames: 'js/[name].js',
assetFileNames: 'assets/[name]-[hash][extname]',
manualChunks: {
'element': ['element-plus']
}
}
}
},
}
})