原文地址:https://blog.csdn.net/weixin_33690963/article/details/88841857
github地址
https://github.com/shuidian/v...
為了充分發揚拿來主義的原則,先放出github地址,clone下來即可測試運行效果。如果覺得還可以的話,請點star,為更多人提供方便。
背景
在實際的開發過程中,單頁應用並不能滿足所有的場景。傳統單頁應用所生成的成果物,在單個系統功能拆分和多個系統靈活組裝時並不方便。舉個例子,我們在A系統中開發了一個實時視頻預覽模塊和一個gis模塊,傳統方式打包A系統,我們會生成一個靜態資源包,這個包,包含了實時視頻預覽模塊和gis模塊在內的所有模塊。那么,現在有一個新的系統要做,碰巧需要原來A系統中的gis模塊,那么我們只能把A系統打包,然后拿過來,通過引入url的方式,只使用其中的一個模塊。這樣做的問題很明顯,我只需要A系統中的一個模塊,但是我要引入整個A系統的資源包,這顯然不合理。那么我們的需求就是從這里產生的,如果我們在開發系統A時,能夠按模塊划分生成多份靜態資源包,最終的成果物中,會有多個子目錄,每個子目錄可獨立運行,完成一個業務功能。這樣的話,我們有任何系統需要我們開發過的任何模塊,都可以直接打包指定的模塊,靈活組裝。
場景分析
首先,這種方案不是完全適合任何場景的,在使用時,還需要注意鑒別是否適用於當前業務場景。下面分析一下這種方式的優缺點:
優點:
1、可與其他系統靈活組裝
2、各個模塊相互不受影響,所以不受框架和開發模式的制約
3、不同模塊可以分開部署
4、后期維護風險小,可以持續的、穩定的進行維護(萬一哪天vue/react/angular被淘汰了,不會受太大影響,每個模塊分別迭代就好)
缺點:
1、各個模塊有相互獨立的資源包,那么如果有相同的資源引用,不能復用
2、模塊的組裝要依賴iframe,所以要對瀏覽器安全設置、cookie共享等問題進行單獨處理
3、用iframe來包裹組件,組件所能控制到的范圍就是其所在的iframe,當涉及到全屏的應用場景時,會比較麻煩
4、不同組件之間的通信比較麻煩
以上只是分析應用場景,下面重點講解一下如何實現多模塊獨立打包。
我們的目標
vue-cli默認打包方式的成果物與我們修改后生成的成果物結構對比如下:
上圖為默認配置下,打包成果物的目錄結構,下圖為我們修改配置后,打包成果物的目錄結構
思路分析
我們最終輸出的成果物是多個獨立的目錄,那么我們就應該區分這些模塊,最好的方式就是每個模塊的代碼放在不同的目錄中,所以我們需要在src中創建每個模塊的目錄。暫時我們以a,b,c三個模塊為例,由於我們現在的項目是多模塊的,每個模塊都應該有獨立的入口,所以我們修改src目錄結構如下:
其他目錄你怎么命名,以及要不要都無所謂,主要是modules目錄,我們會在下面創建若干個模塊。原來的src下的main.js、index.html和app.vue已經沒用了,可以刪掉了。然后模塊內的目錄結構如下圖所示:
聰明的同學已經看出來了,這里其實就是跟原來的src下的main.js、index.html和app.vue一樣的,只不過我們把main.js改成了index.js而已。那么如果模塊內要使用路由、狀態管理都可以根據自己的需求去配置了,如何配置就不在這里討論了。
那么如何從這些模塊開始,把項目最終編譯成三個獨立的靜態資源包呢?簡單來說,其實就是循環跑三次打包腳本,每次打包一個模塊,然后修改一下文件輸出路徑,把編譯好的文件輸出到dist目錄下的a,b,c目錄中。這樣最基本的模塊分開打包功能就完成了,但是還有以下一些問題需要處理。
1、這樣打出的包,各個模塊彼此獨立。如果有這些模塊是在一個系統中使用的,那么應該把多個模塊重復的東西抽取出來復用。
2、如果只需要系統中的部分模塊,那么應該只打包需要的模塊,並且把需要打包的模塊之間的重復代碼抽取出來復用。
問題解決方案
針對第一個問題:實質上只要把webpack配置成多入口的方式即可,這樣在編譯時webpack可以把模塊之間的重復代碼抽取出來,最終的成果物就是一個靜態資源包加多個html文件。這種方式的成果物目錄結構如下:
針對第二個問題:其實跟第一個問題一樣,只不過把webpack的入口配置成可變的就可以了,需要打包哪些模塊,就把入口設置為哪些模塊即可。這種方式的成果物目錄如下(假設要打包a,c兩個模塊):
修改webpack配置的詳細步驟
第一步:增加build/module-conf.js用來處理獲取模塊目錄等問題
var chalk = require('chalk') var glob = require('glob') // 獲取所有的moduleList var moduleList = [] var moduleSrcArray = glob.sync('./src/modules/*') for(var x in moduleSrcArray){ moduleList.push(moduleSrcArray[x].split('/')[3]) } // 檢測是否在輸入的參數是否在允許的list中 var checkModule = function () { var module = process.env.MODULE_ENV // 檢查moduleList是否有重復 var hash = {} var repeatList = [] for(var l = 0;l < moduleList.length; l++){ if(hash[moduleList[l]]){ repeatList.push(moduleList[l]) } hash[moduleList[l]] = true } if(repeatList.length > 0){ console.log(chalk.red('moduleList 有重復:')) console.log(chalk.red(repeatList.toString())) return false } let result = true let illegalParam = '' for (let moduleToBuild of module.split(',')) { if (moduleList.indexOf(moduleToBuild) === -1) { result = false illegalParam = moduleToBuild break } } if(result === false){ console.log(chalk.red('參數錯誤,允許的參數為:')) console.log(chalk.green(moduleList.toString())) console.log(chalk.yellow(`非法參數:${illegalParam}`)) } return result } // 獲取當前要打包的模塊列表 function getModuleToBuild () { let moduleToBuild = [] if (process.env.NODE_ENV === 'production') { /* 部署態,構建要打包的模塊列表,如果指定了要打包的模塊,那么按照指定的模塊配置入口 * 這里有個特性,即使參數未傳,那么獲取到的undefined也是字符串類型的,不是undefined類型 * */ if (process.env.MODULE_ENV !== 'undefined') { moduleToBuild = process.env.MODULE_ENV.split(',') } else { // 如果未指定要打包的模塊,那么打包所有模塊 moduleToBuild = moduleList } } else { // 開發態,獲取所有的模塊列表 moduleToBuild = moduleList } return moduleToBuild } exports.moduleList = moduleList exports.checkModule = checkModule exports.getModuleToBuild = getModuleToBuild
第二步:增加build/build-all.js用來處理循環執行打包命令
const path = require('path') const execFileSync = require('child_process').execFileSync; const moduleList = require('./module-conf').moduleList || [] const buildFile = path.join(__dirname, 'build.js') for( const module of moduleList){ console.log('正在編譯:',module) // 異步執行構建文件,並傳入兩個參數,module:當前打包模塊,separate:當前打包模式(分開打包) execFileSync( 'node', [buildFile, module, 'separate'], {}) }
第三步:修改build/build.js增加MODULE_ENV參數,用來記錄當前打包的模塊名稱,增加MODE_ENV參數,用來記錄當前打包的模式
-
-
require('./check-versions')()
-
const chalk = require('chalk')
-
-
process.env.NODE_ENV = 'production'
-
// MODULE_ENV用來記錄當前打包的模塊名稱
-
process.env.MODULE_ENV = process.argv[ 2]
-
// MODE_ENV用來記錄當前打包的模式,total代表整體打包(靜態資源在同一個目錄下,可以復用重復的文件),separate代表分開打包(靜態資源按模塊名稱分別獨立打包,不能復用重復的文件)
-
process.env.MODE_ENV = process.argv[ 3]
-
-
// 如果有傳參時,對傳入的參數進行檢測,如果參數非法,那么停止打包操作
-
const checkModule = require('./module-conf').checkModule
-
if (process.env.MODULE_ENV !== 'undefined' && !checkModule()) {
-
return
-
}
-
-
const path = require('path')
-
const ora = require('ora')
-
const rm = require('rimraf')
-
const webpack = require('webpack')
-
const config = require('../config')
-
const webpackConfig = require('./webpack.prod.conf')
-
-
const spinner = ora('building for production...')
-
spinner.start()
-
-
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
-
if (err) throw err
-
webpack(webpackConfig, (err, stats) => {
-
spinner.stop()
-
if (err) throw err
-
process.stdout.write(stats.toString({
-
colors: true,
-
modules: false,
-
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
-
chunks: false,
-
chunkModules: false
-
}) + '\n\n')
-
-
if (stats.hasErrors()) {
-
console.log(chalk.red(' Build failed with errors.\n'))
-
process.exit( 1)
-
}
-
-
console.log(chalk.cyan(' Build complete.\n'))
-
console.log(chalk.yellow(
-
' Tip: built files are meant to be served over an HTTP server.\n' +
-
' Opening index.html over file:// won\'t work.\n'
-
))
-
})
-
})
第四步:修改config/index.js的配置,修改打包時的出口目錄配置、html入口模板的配置以及靜態資源路徑配置
-
-
// Template version: 1.3.1
-
// see http://vuejs-templates.github.io/webpack for documentation.
-
-
const path = require('path')
-
-
const MODULE = process.env.MODULE_ENV || 'undefined'
-
// 入口模板路徑
-
const htmlTemplate = `./src/modules/${MODULE}/index.html`
-
-
module.exports = {
-
dev: {
-
-
// Paths
-
assetsSubDirectory: 'static',
-
assetsPublicPath: '/',
-
proxyTable: {},
-
-
// Various Dev Server settings
-
host: 'localhost', // can be overwritten by process.env.HOST
-
port: 8086, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
-
autoOpenBrowser: false,
-
errorOverlay: true,
-
notifyOnErrors: true,
-
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
-
-
// Use Eslint Loader?
-
// If true, your code will be linted during bundling and
-
// linting errors and warnings will be shown in the console.
-
useEslint: true,
-
// If true, eslint errors and warnings will also be shown in the error overlay
-
// in the browser.
-
showEslintErrorsInOverlay: false,
-
-
/**
-
* Source Maps
-
*/
-
-
// https://webpack.js.org/configuration/devtool/#development
-
devtool: 'cheap-module-eval-source-map',
-
-
// If you have problems debugging vue-files in devtools,
-
// set this to false - it *may* help
-
// https://vue-loader.vuejs.org/en/options.html#cachebusting
-
cacheBusting: true,
-
-
cssSourceMap: true
-
},
-
-
build: {
-
// Template for index.html
-
index: path.resolve(__dirname, '../dist', MODULE, 'index.html'),
-
// 加入html入口
-
htmlTemplate: htmlTemplate,
-
// Paths
-
// assetsRoot: path.resolve(__dirname, '../dist', MODULE),
-
// 這里判斷一下打包的模式,如果是分開打包,要把成果物放到以模塊命名的文件夾中
-
assetsRoot: process.env.MODE_ENV === 'separate' ? path.resolve(__dirname, '../dist', MODULE) : path.resolve(__dirname, '../dist'),
-
assetsSubDirectory: 'static',
-
// 這里的路徑改成相對路徑,原來是assetsPublicPath: '/',
-
// assetsPublicPath: '/',
-
assetsPublicPath: '',
-
-
/**
-
* Source Maps
-
*/
-
-
productionSourceMap: true,
-
// https://webpack.js.org/configuration/devtool/#production
-
devtool: '#source-map',
-
-
// Gzip off by default as many popular static hosts such as
-
// Surge or Netlify already gzip all static assets for you.
-
// Before setting to `true`, make sure to:
-
// npm install --save-dev compression-webpack-plugin
-
productionGzip: false,
-
productionGzipExtensions: ['js', 'css'],
-
-
// Run the build command with an extra argument to
-
// View the bundle analyzer report after build finishes:
-
// `npm run build --report`
-
// Set to `true` or `false` to always turn it on or off
-
bundleAnalyzerReport: process.env.npm_config_report
-
}
-
}
第五步:修改webpack.base.conf.js的入口配置,根據傳參,動態配置入口文件
-
entry() {
-
// 初始化入口配置
-
const entry = {}
-
// 所有模塊的列表
-
const moduleToBuild = require('./module-conf').getModuleToBuild() || []
-
// 根據傳入的待打包目錄名稱,構建多入口配置
-
for (let module of moduleToBuild) {
-
entry[ module] = `./src/modules/${module}/index.js`
-
}
-
return entry
-
},
第六步:修改webpack.dev.conf.js的配置,增加多入口時webpackHtmlPlugin插件的配置,增加靜態資源服務器的配置
-
-
const utils = require('./utils')
-
const webpack = require('webpack')
-
const config = require('../config')
-
const merge = require('webpack-merge')
-
const path = require('path')
-
const baseWebpackConfig = require('./webpack.base.conf')
-
const CopyWebpackPlugin = require('copy-webpack-plugin')
-
const HtmlWebpackPlugin = require('html-webpack-plugin')
-
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
-
const portfinder = require('portfinder')
-
-
const HOST = process.env.HOST
-
const PORT = process.env.PORT && Number(process.env.PORT)
-
const moduleList = require('./module-conf').moduleList || []
-
// 組裝多個(有幾個module就有幾個htmlWebpackPlugin)htmlWebpackPlugin,然后追加到配置中
-
const htmlWebpackPlugins = []
-
for (let module of moduleList) {
-
htmlWebpackPlugins.push( new HtmlWebpackPlugin({
-
filename: `${module}/index.html`,
-
template: `./src/modules/${module}/index.html`,
-
inject: true,
-
chunks: [module]
-
}))
-
}
-
-
const devWebpackConfig = merge(baseWebpackConfig, {
-
module: {
-
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
-
},
-
// cheap-module-eval-source-map is faster for development
-
devtool: config.dev.devtool,
-
-
// these devServer options should be customized in /config/index.js
-
devServer: {
-
clientLogLevel: 'warning',
-
historyApiFallback: {
-
rewrites: [
-
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
-
],
-
},
-
hot: true,
-
contentBase: false, // since we use CopyWebpackPlugin.
-
compress: true,
-
host: HOST || config.dev.host,
-
port: PORT || config.dev.port,
-
open: config.dev.autoOpenBrowser,
-
overlay: config.dev.errorOverlay
-
? { warnings: false, errors: true }
-
: false,
-
publicPath: config.dev.assetsPublicPath,
-
proxy: config.dev.proxyTable,
-
quiet: true, // necessary for FriendlyErrorsPlugin
-
watchOptions: {
-
poll: config.dev.poll,
-
},
-
setup(app) {
-
// 寫個小路由,打開瀏覽器的時候可以選一個開發路徑
-
let html = `<html><head><title>調試頁面</title>`
-
html += `<style>body{margin: 0}.module-menu{float: left;width: 200px;height: 100%;padding: 0 8px;border-right: 1px solid #00ffff;box-sizing: border-box}.module-container{float: left;width: calc(100% - 200px);height: 100%}.module-container iframe{width: 100%;height: 100%}</style>`
-
html += `</head><body><div class="module-menu">`
-
for(let module of moduleList){
-
html += `<a href="/${module}/index.html" target="container">${module.toString()}</a><br>`
-
}
-
html += `</div>`
-
html += `<div class="module-container"><iframe src="/${moduleList[0]}/index.html" name="container" frameborder="0"></iframe></div>`
-
html += `</body></html>`
-
// let sentHref = ''
-
// for(var module in moduleList){
-
// sentHref += '<a href="/'+ moduleList[module] +'/index.html">點我調試模塊:'+ moduleList[module].toString() +'</a> <br>'
-
// }
-
app.get( '/moduleList', (req, res, next) => {
-
res.send(html)
-
})
-
// 訪問根路徑時重定向到moduleList
-
app.get( '/', (req, res, next) => {
-
res.redirect( '/moduleList')
-
})
-
}
-
},
-
plugins: [
-
new webpack.DefinePlugin({
-
'process.env': require('../config/dev.env')
-
}),
-
new webpack.HotModuleReplacementPlugin(),
-
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
-
new webpack.NoEmitOnErrorsPlugin(),
-
// copy custom static assets
-
new CopyWebpackPlugin([
-
{
-
from: path.resolve(__dirname, '../static'),
-
to: config.dev.assetsSubDirectory,
-
ignore: ['.*']
-
}
-
]),
-
// https://github.com/ampedandwired/html-webpack-plugin
-
// new HtmlWebpackPlugin({
-
// filename: 'a/index.html',
-
// template: './src/modules/a/index.html',
-
// inject: true,
-
// chunks: ['a']
-
// }),
-
].concat(htmlWebpackPlugins)
-
})
-
-
module.exports = new Promise((resolve, reject) => {
-
portfinder.basePort = process.env.PORT || config.dev.port
-
portfinder.getPort( (err, port) => {
-
if (err) {
-
reject(err)
-
} else {
-
// publish the new Port, necessary for e2e tests
-
process.env.PORT = port
-
// add port to devServer config
-
devWebpackConfig.devServer.port = port
-
-
// Add FriendlyErrorsPlugin
-
devWebpackConfig.plugins.push( new FriendlyErrorsPlugin({
-
compilationSuccessInfo: {
-
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
-
},
-
onErrors: config.dev.notifyOnErrors
-
? utils.createNotifierCallback()
-
: undefined
-
}))
-
-
resolve(devWebpackConfig)
-
}
-
})
-
})
第七步:修改webpack.prod.conf.js的配置,增加對不同打包模式的處理。
-
-
const path = require('path')
-
const utils = require('./utils')
-
const webpack = require('webpack')
-
const config = require('../config')
-
const merge = require('webpack-merge')
-
const baseWebpackConfig = require('./webpack.base.conf')
-
const CopyWebpackPlugin = require('copy-webpack-plugin')
-
const HtmlWebpackPlugin = require('html-webpack-plugin')
-
const ExtractTextPlugin = require('extract-text-webpack-plugin')
-
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
-
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
-
-
const env = process.env.NODE_ENV === 'testing'
-
? require('../config/test.env')
-
: require('../config/prod.env')
-
// 獲取所有模塊列表
-
const moduleToBuild = require('./module-conf').getModuleToBuild() || []
-
// 組裝多個(有幾個module就有幾個htmlWebpackPlugin)htmlWebpackPlugin,然后追加到配置中
-
const htmlWebpackPlugins = []
-
// 判斷一下是否為分開打包模式
-
if (process.env.MODE_ENV === 'separate') {
-
// 分開打包時是通過重復運行指定模塊打包命令實現的,所以每次都是單個html文件,只要配置一個htmlPlugin
-
htmlWebpackPlugins.push( new HtmlWebpackPlugin({
-
filename: process.env.NODE_ENV === 'testing'
-
? 'index.html'
-
: config.build.index,
-
// template: 'index.html',
-
template: config.build.htmlTemplate,
-
inject: true,
-
minify: {
-
removeComments: true,
-
collapseWhitespace: true,
-
removeAttributeQuotes: true
-
// more options:
-
// https://github.com/kangax/html-minifier#options-quick-reference
-
},
-
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
-
chunksSortMode: 'dependency'
-
}))
-
} else {
-
// 一起打包時是通過多入口實現的,所以要配置多個htmlPlugin
-
for (let module of moduleToBuild) {
-
htmlWebpackPlugins.push( new HtmlWebpackPlugin({
-
filename: `${module}.html`,
-
template: `./src/modules/${module}/index.html`,
-
inject: true,
-
// 這里要指定把哪些chunks追加到html中,默認會把所有入口的chunks追加到html中,這樣是不行的
-
chunks: [ 'vendor', 'manifest', module],
-
// filename: process.env.NODE_ENV === 'testing'
-
// ? 'index.html'
-
// : config.build.index,
-
// template: 'index.html',
-
minify: {
-
removeComments: true,
-
collapseWhitespace: true,
-
removeAttributeQuotes: true
-
// more options:
-
// https://github.com/kangax/html-minifier#options-quick-reference
-
},
-
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
-
chunksSortMode: 'dependency'
-
}))
-
}
-
}
-
-
// 獲取當前打包的目錄名稱
-
const webpackConfig = merge(baseWebpackConfig, {
-
module: {
-
rules: utils.styleLoaders({
-
sourceMap: config.build.productionSourceMap,
-
extract: true,
-
usePostCSS: true
-
})
-
},
-
devtool: config.build.productionSourceMap ? config.build.devtool : false,
-
output: {
-
path: config.build.assetsRoot,
-
filename: utils.assetsPath('js/[name].[chunkhash].js'),
-
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
-
},
-
plugins: [
-
// http://vuejs.github.io/vue-loader/en/workflow/production.html
-
new webpack.DefinePlugin({
-
'process.env': env
-
}),
-
new UglifyJsPlugin({
-
uglifyOptions: {
-
compress: {
-
warnings: false
-
}
-
},
-
sourceMap: config.build.productionSourceMap,
-
parallel: true
-
}),
-
// extract css into its own file
-
new ExtractTextPlugin({
-
filename: utils.assetsPath('css/[name].[contenthash].css'),
-
// Setting the following option to `false` will not extract CSS from codesplit chunks.
-
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
-
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
-
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
-
allChunks: true,
-
}),
-
// Compress extracted CSS. We are using this plugin so that possible
-
// duplicated CSS from different components can be deduped.
-
new OptimizeCSSPlugin({
-
cssProcessorOptions: config.build.productionSourceMap
-
? { safe: true, map: { inline: false } }
-
: { safe: true }
-
}),
-
// generate dist index.html with correct asset hash for caching.
-
// you can customize output by editing /index.html
-
// see https://github.com/ampedandwired/html-webpack-plugin
-
/*
-
new HtmlWebpackPlugin({
-
filename: process.env.NODE_ENV === 'testing'
-
? 'index.html'
-
: config.build.index,
-
// template: 'index.html',
-
template: config.build.htmlTemplate,
-
inject: true,
-
minify: {
-
removeComments: true,
-
collapseWhitespace: true,
-
removeAttributeQuotes: true
-
// more options:
-
// https://github.com/kangax/html-minifier#options-quick-reference
-
},
-
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
-
chunksSortMode: 'dependency'
-
}),
-
*/
-
// keep module.id stable when vendor modules does not change
-
new webpack.HashedModuleIdsPlugin(),
-
// enable scope hoisting
-
new webpack.optimize.ModuleConcatenationPlugin(),
-
// split vendor js into its own file
-
new webpack.optimize.CommonsChunkPlugin({
-
name: 'vendor',
-
minChunks ( module) {
-
// any required modules inside node_modules are extracted to vendor
-
return (
-
module.resource &&
-
/\.js$/.test(module.resource) &&
-
module.resource.indexOf(
-
path.join(__dirname, '../node_modules')
-
) === 0
-
)
-
}
-
}),
-
// extract webpack runtime and module manifest to its own file in order to
-
// prevent vendor hash from being updated whenever app bundle is updated
-
new webpack.optimize.CommonsChunkPlugin({
-
name: 'manifest',
-
minChunks: Infinity
-
}),
-
// This instance extracts shared chunks from code splitted chunks and bundles them
-
// in a separate chunk, similar to the vendor chunk
-
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
-
new webpack.optimize.CommonsChunkPlugin({
-
name: 'app',
-
async: 'vendor-async',
-
children: true,
-
minChunks: 3
-
}),
-
-
// copy custom static assets
-
new CopyWebpackPlugin([
-
{
-
from: path.resolve(__dirname, '../static'),
-
to: config.build.assetsSubDirectory,
-
ignore: ['.*']
-
}
-
])
-
].concat(htmlWebpackPlugins)
-
})
-
-
if (config.build.productionGzip) {
-
const CompressionWebpackPlugin = require('compression-webpack-plugin')
-
-
webpackConfig.plugins.push(
-
new CompressionWebpackPlugin({
-
asset: '[path].gz[query]',
-
algorithm: 'gzip',
-
test: new RegExp(
-
'\\.(' +
-
config.build.productionGzipExtensions.join( '|') +
-
')$'
-
),
-
threshold: 10240,
-
minRatio: 0.8
-
})
-
)
-
}
-
-
if (config.build.bundleAnalyzerReport) {
-
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
-
webpackConfig.plugins.push( new BundleAnalyzerPlugin())
-
}
-
-
module.exports = webpackConfig
第八步:修改package.json,增加npm run build-all指令
-
"scripts": {
-
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
-
"start": "npm run dev",
-
"unit": "jest --config test/unit/jest.conf.js --coverage",
-
"test": "npm run unit",
-
"lint": "eslint --ext .js,.vue src test/unit",
-
"build": "node build/build.js",
-
"build-all": "node build/build-all.js"
-
},
構建指令
npm run build // 打包全部模塊到一個資源包下面,每個模塊的入口是module.html文件,靜態資源都在static目錄中,這種方式可以復用重復的資源
npm run build moduleName1,moduleName2,... // 打包指定模塊到一個資源包下面,每個模塊的入口是module.html文件,靜態資源都在static目錄中,這種方式可以復用重復的資源
npm run build-all // 打包所有模塊,然后每個模塊彼此獨立,有幾個模塊,就產生幾個靜態資源包,這種方式不會復用重復的資源
本文是在參考了以下文章的內容之后寫的,在原有的基礎上做了一些擴展,支持多入口模式
參考資料:https://segmentfault.com/a/11...
注意事項
鑒於評論區疑問比較多的地方,這里我統一解釋一下:路由到底是怎么配的?
當項目模板clone到本地跑起來之后,你會看到這樣的界面:
在這個界面中,需要注意的兩個點已經標注出來了。我們在使用時,需要在moduls目錄下的子目錄中配置前端路由,也只有這里的路由才是前端能夠控制的。至於那個localhost:8086/a和localhost:8086/b以及localhost:8086/moduleList這幾個路由地址都是用node服務器寫的,跟前端沒有關系,這里大家不要被誤導。
注意事項完。