vue-cli webpack3 扩展多模块打包

场景

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

实现

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

    新建build/entry.jsnode

    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模块,能够查看文档nodejs.cn/api/fs.html nodejs.cn/api/path.ht…,能够根据本身的项目配置更改,此处是以src/modules/文件夹下的目录做为模块,每一个模块中都有一个main.js做为入口文件webpack

    修改build/webpack.base.conf.js中entrygit

    const entryObj = require('./entry')
    module.exports = {
      entry: entryObj
    }
    复制代码
  • 接下来就是如何将打包好的文件注入到html中,这里利用html-webpack-plugin插件来解决这个问题,首先你须要有一个html的模板文件,而后在webpack配置中更改默认的html-webpack-plugin插件配置github

    添加build/plugins.jsweb

    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配置vue-cli

    module.exports = {
        plugins: configPlugins
    }
    复制代码

    生产环境下配置与开发环境思路一致,须要注意的是html-webpack-plugin插件参数不一样,参考原vue-cli的配置api

实战

vue移动web通用脚手架ui

github地址: github.com/GavinZhuLei…

相关文章
相关标签/搜索