https://github.com/shuidian/v...
爲了充分發揚拿來主義的原則,先放出github地址,clone下來便可測試運行效果。若是以爲還能夠的話,請點star,爲更多人提供方便。javascript
在實際的開發過程當中,單頁應用並不能知足全部的場景。傳統單頁應用所生成的成果物,在單個系統功能拆分和多個系統靈活組裝時並不方便。舉個例子,咱們在A系統中開發了一個實時視頻預覽模塊和一個gis模塊,傳統方式打包A系統,咱們會生成一個靜態資源包,這個包,包含了實時視頻預覽模塊和gis模塊在內的全部模塊。那麼,如今有一個新的系統要作,碰巧須要原來A系統中的gis模塊,那麼咱們只能把A系統打包,而後拿過來,經過引入url的方式,只使用其中的一個模塊。這樣作的問題很明顯,我只須要A系統中的一個模塊,可是我要引入整個A系統的資源包,這顯然不合理。那麼咱們的需求就是從這裏產生的,若是咱們在開發系統A時,可以按模塊劃分生成多份靜態資源包,最終的成果物中,會有多個子目錄,每一個子目錄可獨立運行,完成一個業務功能。這樣的話,咱們有任何系統須要咱們開發過的任何模塊,均可以直接打包指定的模塊,靈活組裝。css
首先,這種方案不是徹底適合任何場景的,在使用時,還須要注意鑑別是否適用於當前業務場景。下面分析一下這種方式的優缺點:html
優勢:
一、可與其餘系統靈活組裝
二、各個模塊相互不受影響,因此不受框架和開發模式的制約
三、不一樣模塊能夠分開部署
四、後期維護風險小,能夠持續的、穩定的進行維護(萬一哪天vue/react/angular被淘汰了,不會受太大影響,每一個模塊分別迭代就好)前端
缺點:
一、各個模塊有相互獨立的資源包,那麼若是有相同的資源引用,不能複用
二、模塊的組裝要依賴iframe,因此要對瀏覽器安全設置、cookie共享等問題進行單獨處理
三、用iframe來包裹組件,組件所能控制到的範圍就是其所在的iframe,當涉及到全屏的應用場景時,會比較麻煩
四、不一樣組件之間的通訊比較麻煩vue
以上只是分析應用場景,下面重點講解一下如何實現多模塊獨立打包。java
vue-cli默認打包方式的成果物與咱們修改後生成的成果物結構對好比下:node
上圖爲默認配置下,打包成果物的目錄結構,下圖爲咱們修改配置後,打包成果物的目錄結構react
咱們最終輸出的成果物是多個獨立的目錄,那麼咱們就應該區分這些模塊,最好的方式就是每一個模塊的代碼放在不一樣的目錄中,因此咱們須要在src中建立每一個模塊的目錄。暫時咱們以a,b,c三個模塊爲例,因爲咱們如今的項目是多模塊的,每一個模塊都應該有獨立的入口,因此咱們修改src目錄結構以下:webpack
其餘目錄你怎麼命名,以及要不要都無所謂,主要是modules目錄,咱們會在下面建立若干個模塊。原來的src下的main.js、index.html和app.vue已經沒用了,能夠刪掉了。而後模塊內的目錄結構以下圖所示:git
聰明的同窗已經看出來了,這裏其實就是跟原來的src下的main.js、index.html和app.vue同樣的,只不過咱們把main.js改爲了index.js而已。那麼若是模塊內要使用路由、狀態管理均可以根據本身的需求去配置了,如何配置就不在這裏討論了。
那麼如何從這些模塊開始,把項目最終編譯成三個獨立的靜態資源包呢?簡單來講,其實就是循環跑三次打包腳本,每次打包一個模塊,而後修改一下文件輸出路徑,把編譯好的文件輸出到dist目錄下的a,b,c目錄中。這樣最基本的模塊分開打包功能就完成了,可是還有如下一些問題須要處理。
一、這樣打出的包,各個模塊彼此獨立。若是有這些模塊是在一個系統中使用的,那麼應該把多個模塊重複的東西抽取出來複用。
二、若是隻須要系統中的部分模塊,那麼應該只打包須要的模塊,而且把須要打包的模塊之間的重複代碼抽取出來複用。
針對第一個問題:實質上只要把webpack配置成多入口的方式便可,這樣在編譯時webpack能夠把模塊之間的重複代碼抽取出來,最終的成果物就是一個靜態資源包加多個html文件。這種方式的成果物目錄結構以下:
針對第二個問題:其實跟第一個問題同樣,只不過把webpack的入口配置成可變的就能夠了,須要打包哪些模塊,就把入口設置爲哪些模塊便可。這種方式的成果物目錄以下(假設要打包a,c兩個模塊):
第一步:增長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參數,用來記錄當前打包的模式
'use strict' 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入口模板的配置以及靜態資源路徑配置
'use strict' // 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插件的配置,增長靜態資源服務器的配置
'use strict' 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的配置,增長對不一樣打包模式的處理。
'use strict' 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服務器寫的,跟前端沒有關係,這裏你們不要被誤導。
注意事項完。