場景
在實際的項目開發(fā)中會出現(xiàn)這樣的場景,項目中需要多個模塊(單頁或者多頁應(yīng)用)配合使用的情況,而vue-cli默認(rèn)只提供了單入口打包,所以就想到對vue-cli進行擴展
實現(xiàn)
首先得知道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,可以根據(jù)自己的項目配置更改,此處是以src/modules/文件夾下的目錄作為模塊,每個模塊中都有一個main.js作為入口文件
修改build/webpack.base.conf.js中entry
const entryObj = require('./entry') module.exports = { entry: entryObj }
接下來就是如何將打包好的文件注入到html中,這里利用html-webpack-plugin插件來解決這個問題,首先你需要有一個html的模板文件,然后在webpack配置中更改默認(rèn)的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 }
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
vue select操作組件開啟
封裝Vue2路由導(dǎo)航鉤子并在實戰(zhàn)中使用
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com