为什么要配置多页应用?
场景:pc端单页项目A开发好了,突然需要A中某些资源能单独打包成B资源,单独部署。这时可以配置多页应用解决。
怎么配置?
在package.json构建命令中带入参数,打包配置文件根据不同的参数执行不同的构建逻辑。
**1 vue3+webpack **
1.1 依赖版本:
"dependencies": {
......
"vue": "^3.2.20",
},
1.2 package.json
"scripts": {
"serve": "vue-cli-service serve", //原构建命令---->B与A都构建
"build": "vue-cli-service build",
"serve_b": "vue-cli-service serve --bBuild", // 只构建B资源,--bBuild是自定义参数
"build_b": "vue-cli-service build --bBuild"
},
1.3 vue.config.js
module.exports = () => {
let { argv } = process
if (argv.includes('--bBuild')) { //B单独构建
return {
......
chainWebpack: config => {
// 清空默认入口
config.entryPoints.clear();
//增加新入口
config.entry('app').add('./src/pages/B/main.js') //B的入口js
//修改index.html 默认的路径
config.plugin('html').tap(args => {
args[0].template = './html/B.html' //B的html
return args
})
},
};
} else { //B与A都构建
return {
......
// 多页面配置
pages: {
index: {
entry: 'src/pages/index/main.js', //A的入口js
template: './html/index.html', //A的html
filename: 'index.html',
},
ammeter: {
entry: 'src/pages/B/main.js', //B的入口js
template: './html/B.html', //B的html
//输出文件名,可选项,省略时默认与模块名一致
filename: 'b.html',
}
},
};
}
}
**2 vue3+vite **
1.1 依赖版本:
"dependencies": {
......
"vue": "^3.4.21",
},
"devDependencies": {
......
"vite": "^5.1.6"
}
1.2 package.json
"scripts": {
"dev": "vite",
"dev:b": "vite -- --bBuild", // 只构建B资源,--bBuild是自定义参数
"build": "vite build",
"build:b": "vite build -- --bBuild", // 只构建B资源,--bBuild是自定义参数
},
1.3 vite.config.js
export default defineConfig(({ mode }) => {
if (process.argv.includes('--bBuild')) {//只构建B资源
return {
// 开发环境自动打开index.B.html
server: {
open: 'index.B.html' // B资源对应的html
},
//生产环境构建B资源
build: {
......
rollupOptions: {
input: 'index.B.html' // B资源对应的html
},
}
}
} else {
//构建B与A
return {
......
//生产环境整体构建
build: {
......
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'), // A对应的html
monitor: resolve(__dirname, 'index.B.html')// B资源对应的html
}
}
}
}
}
})