vue-cli webpack3扩展多模块打包

时间:2023-03-09 01:39:58
vue-cli webpack3扩展多模块打包

场景

在实际的项目开发中会出现这样的场景,项目中需要多个模块(单页或者多页应用)配合使用的情况,而vue-cli默认只提供了单入口打包,所以就想到对vue-cli进行扩展

实现

首先得知道webpack是提供了多入口打包,那就可以从这里开始改造

新建build/entry.js

 const path = require('path')
const fs = require('fs') const moduleDir = path.resolve(__dirname, '../src/modules') let entryObj = {} let moduleItems = fs.readdirSync(moduleDir) moduleItems.forEach(item => {
entryObj[`${item}`] = `./src/modules/${item}/main.js`
}) module.exports = entryObj
这里用到了nodejs的fs和path模块,可以查看文档http://nodejs.cn/api/fs.html,http://nodejs.cn/api/path.html,可以根据自己的项目配置更改,此处是以src/modules/文件夹下的目录作为模块,每个模块中都有一个main.js作为入口文件
修改build/webpack.base.conf.js中entry
const entryObj = require('./entry')
module.exports = {
entry: entryObj
}

下来就是如何将打包好的文件注入到html中,这里利用html-webpack-plugin插件来解决这个问题,首先你需要有一个html的模板文件,然后在webpack配置中更改默认的html-webpack-plugin插件配置

添加build/plugins.js

const HtmlWebpackPlugin = require('html-webpack-plugin')

let configPlugins = []

Object.keys(entryObj).forEach(item => {
configPlugins.push(new HtmlWebpackPlugin(
{
filename: '../dist/' + item + '.html',
template: path.resolve(__dirname, '../index.html'),
chunks: [item]
}
))
}) module.exports = configPlugins

修改build/webpack.dev.conf.js配置

module.exports = {
plugins: configPlugins
}

实战

vue移动web通用脚手架

github地址: https://github.com/GavinZhuLei/vue-mobile