vue-cli扩展多模块打包的示例代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue-cli扩展多模块打包的示例代码

Gavin_lei   2020-05-16 我要评论

场景

在实际的项目开发中会出现这样的场景,项目中需要多个模块(单页或者多页应用)配合使用的情况,而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.htmlhttp://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: '..https://img.qb5200.com/download-x/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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们