基於vue-cli搭建多模塊且各模塊獨立打包的項目


原文地址: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默認打包方式的成果物與我們修改后生成的成果物結構對比如下:

clipboard.png
clipboard.png

上圖為默認配置下,打包成果物的目錄結構,下圖為我們修改配置后,打包成果物的目錄結構

思路分析

我們最終輸出的成果物是多個獨立的目錄,那么我們就應該區分這些模塊,最好的方式就是每個模塊的代碼放在不同的目錄中,所以我們需要在src中創建每個模塊的目錄。暫時我們以a,b,c三個模塊為例,由於我們現在的項目是多模塊的,每個模塊都應該有獨立的入口,所以我們修改src目錄結構如下:

clipboard.png

其他目錄你怎么命名,以及要不要都無所謂,主要是modules目錄,我們會在下面創建若干個模塊。原來的src下的main.js、index.html和app.vue已經沒用了,可以刪掉了。然后模塊內的目錄結構如下圖所示:

clipboard.png

聰明的同學已經看出來了,這里其實就是跟原來的src下的main.js、index.html和app.vue一樣的,只不過我們把main.js改成了index.js而已。那么如果模塊內要使用路由、狀態管理都可以根據自己的需求去配置了,如何配置就不在這里討論了。

那么如何從這些模塊開始,把項目最終編譯成三個獨立的靜態資源包呢?簡單來說,其實就是循環跑三次打包腳本,每次打包一個模塊,然后修改一下文件輸出路徑,把編譯好的文件輸出到dist目錄下的a,b,c目錄中。這樣最基本的模塊分開打包功能就完成了,但是還有以下一些問題需要處理。

1、這樣打出的包,各個模塊彼此獨立。如果有這些模塊是在一個系統中使用的,那么應該把多個模塊重復的東西抽取出來復用。
2、如果只需要系統中的部分模塊,那么應該只打包需要的模塊,並且把需要打包的模塊之間的重復代碼抽取出來復用。

問題解決方案

針對第一個問題:實質上只要把webpack配置成多入口的方式即可,這樣在編譯時webpack可以把模塊之間的重復代碼抽取出來,最終的成果物就是一個靜態資源包加多個html文件。這種方式的成果物目錄結構如下:

clipboard.png

針對第二個問題:其實跟第一個問題一樣,只不過把webpack的入口配置成可變的就可以了,需要打包哪些模塊,就把入口設置為哪些模塊即可。這種方式的成果物目錄如下(假設要打包a,c兩個模塊):

clipboard.png

修改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參數,用來記錄當前打包的模式

  1.  
    'use strict'
  2.  
    require('./check-versions')()
  3.  
    const chalk = require('chalk')
  4.  
     
  5.  
    process.env.NODE_ENV = 'production'
  6.  
    // MODULE_ENV用來記錄當前打包的模塊名稱
  7.  
    process.env.MODULE_ENV = process.argv[ 2]
  8.  
    // MODE_ENV用來記錄當前打包的模式,total代表整體打包(靜態資源在同一個目錄下,可以復用重復的文件),separate代表分開打包(靜態資源按模塊名稱分別獨立打包,不能復用重復的文件)
  9.  
    process.env.MODE_ENV = process.argv[ 3]
  10.  
     
  11.  
    // 如果有傳參時,對傳入的參數進行檢測,如果參數非法,那么停止打包操作
  12.  
    const checkModule = require('./module-conf').checkModule
  13.  
    if (process.env.MODULE_ENV !== 'undefined' && !checkModule()) {
  14.  
    return
  15.  
    }
  16.  
     
  17.  
    const path = require('path')
  18.  
    const ora = require('ora')
  19.  
    const rm = require('rimraf')
  20.  
    const webpack = require('webpack')
  21.  
    const config = require('../config')
  22.  
    const webpackConfig = require('./webpack.prod.conf')
  23.  
     
  24.  
    const spinner = ora('building for production...')
  25.  
    spinner.start()
  26.  
     
  27.  
    rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  28.  
    if (err) throw err
  29.  
    webpack(webpackConfig, (err, stats) => {
  30.  
    spinner.stop()
  31.  
    if (err) throw err
  32.  
    process.stdout.write(stats.toString({
  33.  
    colors: true,
  34.  
    modules: false,
  35.  
    children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
  36.  
    chunks: false,
  37.  
    chunkModules: false
  38.  
    }) + '\n\n')
  39.  
     
  40.  
    if (stats.hasErrors()) {
  41.  
    console.log(chalk.red(' Build failed with errors.\n'))
  42.  
    process.exit( 1)
  43.  
    }
  44.  
     
  45.  
    console.log(chalk.cyan(' Build complete.\n'))
  46.  
    console.log(chalk.yellow(
  47.  
    ' Tip: built files are meant to be served over an HTTP server.\n' +
  48.  
    ' Opening index.html over file:// won\'t work.\n'
  49.  
    ))
  50.  
    })
  51.  
    })

第四步:修改config/index.js的配置,修改打包時的出口目錄配置、html入口模板的配置以及靜態資源路徑配置

  1.  
    'use strict'
  2.  
    // Template version: 1.3.1
  3.  
    // see http://vuejs-templates.github.io/webpack for documentation.
  4.  
     
  5.  
    const path = require('path')
  6.  
     
  7.  
    const MODULE = process.env.MODULE_ENV || 'undefined'
  8.  
    // 入口模板路徑
  9.  
    const htmlTemplate = `./src/modules/${MODULE}/index.html`
  10.  
     
  11.  
    module.exports = {
  12.  
    dev: {
  13.  
     
  14.  
    // Paths
  15.  
    assetsSubDirectory: 'static',
  16.  
    assetsPublicPath: '/',
  17.  
    proxyTable: {},
  18.  
     
  19.  
    // Various Dev Server settings
  20.  
    host: 'localhost', // can be overwritten by process.env.HOST
  21.  
    port: 8086, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
  22.  
    autoOpenBrowser: false,
  23.  
    errorOverlay: true,
  24.  
    notifyOnErrors: true,
  25.  
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
  26.  
     
  27.  
    // Use Eslint Loader?
  28.  
    // If true, your code will be linted during bundling and
  29.  
    // linting errors and warnings will be shown in the console.
  30.  
    useEslint: true,
  31.  
    // If true, eslint errors and warnings will also be shown in the error overlay
  32.  
    // in the browser.
  33.  
    showEslintErrorsInOverlay: false,
  34.  
     
  35.  
    /**
  36.  
    * Source Maps
  37.  
    */
  38.  
     
  39.  
    // https://webpack.js.org/configuration/devtool/#development
  40.  
    devtool: 'cheap-module-eval-source-map',
  41.  
     
  42.  
    // If you have problems debugging vue-files in devtools,
  43.  
    // set this to false - it *may* help
  44.  
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
  45.  
    cacheBusting: true,
  46.  
     
  47.  
    cssSourceMap: true
  48.  
    },
  49.  
     
  50.  
    build: {
  51.  
    // Template for index.html
  52.  
    index: path.resolve(__dirname, '../dist', MODULE, 'index.html'),
  53.  
    // 加入html入口
  54.  
    htmlTemplate: htmlTemplate,
  55.  
    // Paths
  56.  
    // assetsRoot: path.resolve(__dirname, '../dist', MODULE),
  57.  
    // 這里判斷一下打包的模式,如果是分開打包,要把成果物放到以模塊命名的文件夾中
  58.  
    assetsRoot: process.env.MODE_ENV === 'separate' ? path.resolve(__dirname, '../dist', MODULE) : path.resolve(__dirname, '../dist'),
  59.  
    assetsSubDirectory: 'static',
  60.  
    // 這里的路徑改成相對路徑,原來是assetsPublicPath: '/',
  61.  
    // assetsPublicPath: '/',
  62.  
    assetsPublicPath: '',
  63.  
     
  64.  
    /**
  65.  
    * Source Maps
  66.  
    */
  67.  
     
  68.  
    productionSourceMap: true,
  69.  
    // https://webpack.js.org/configuration/devtool/#production
  70.  
    devtool: '#source-map',
  71.  
     
  72.  
    // Gzip off by default as many popular static hosts such as
  73.  
    // Surge or Netlify already gzip all static assets for you.
  74.  
    // Before setting to `true`, make sure to:
  75.  
    // npm install --save-dev compression-webpack-plugin
  76.  
    productionGzip: false,
  77.  
    productionGzipExtensions: ['js', 'css'],
  78.  
     
  79.  
    // Run the build command with an extra argument to
  80.  
    // View the bundle analyzer report after build finishes:
  81.  
    // `npm run build --report`
  82.  
    // Set to `true` or `false` to always turn it on or off
  83.  
    bundleAnalyzerReport: process.env.npm_config_report
  84.  
    }
  85.  
    }

第五步:修改webpack.base.conf.js的入口配置,根據傳參,動態配置入口文件

  1.  
    entry() {
  2.  
    // 初始化入口配置
  3.  
    const entry = {}
  4.  
    // 所有模塊的列表
  5.  
    const moduleToBuild = require('./module-conf').getModuleToBuild() || []
  6.  
    // 根據傳入的待打包目錄名稱,構建多入口配置
  7.  
    for (let module of moduleToBuild) {
  8.  
    entry[ module] = `./src/modules/${module}/index.js`
  9.  
    }
  10.  
    return entry
  11.  
    },

第六步:修改webpack.dev.conf.js的配置,增加多入口時webpackHtmlPlugin插件的配置,增加靜態資源服務器的配置

  1.  
    'use strict'
  2.  
    const utils = require('./utils')
  3.  
    const webpack = require('webpack')
  4.  
    const config = require('../config')
  5.  
    const merge = require('webpack-merge')
  6.  
    const path = require('path')
  7.  
    const baseWebpackConfig = require('./webpack.base.conf')
  8.  
    const CopyWebpackPlugin = require('copy-webpack-plugin')
  9.  
    const HtmlWebpackPlugin = require('html-webpack-plugin')
  10.  
    const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
  11.  
    const portfinder = require('portfinder')
  12.  
     
  13.  
    const HOST = process.env.HOST
  14.  
    const PORT = process.env.PORT && Number(process.env.PORT)
  15.  
    const moduleList = require('./module-conf').moduleList || []
  16.  
    // 組裝多個(有幾個module就有幾個htmlWebpackPlugin)htmlWebpackPlugin,然后追加到配置中
  17.  
    const htmlWebpackPlugins = []
  18.  
    for (let module of moduleList) {
  19.  
    htmlWebpackPlugins.push( new HtmlWebpackPlugin({
  20.  
    filename: `${module}/index.html`,
  21.  
    template: `./src/modules/${module}/index.html`,
  22.  
    inject: true,
  23.  
    chunks: [module]
  24.  
    }))
  25.  
    }
  26.  
     
  27.  
    const devWebpackConfig = merge(baseWebpackConfig, {
  28.  
    module: {
  29.  
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  30.  
    },
  31.  
    // cheap-module-eval-source-map is faster for development
  32.  
    devtool: config.dev.devtool,
  33.  
     
  34.  
    // these devServer options should be customized in /config/index.js
  35.  
    devServer: {
  36.  
    clientLogLevel: 'warning',
  37.  
    historyApiFallback: {
  38.  
    rewrites: [
  39.  
    { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
  40.  
    ],
  41.  
    },
  42.  
    hot: true,
  43.  
    contentBase: false, // since we use CopyWebpackPlugin.
  44.  
    compress: true,
  45.  
    host: HOST || config.dev.host,
  46.  
    port: PORT || config.dev.port,
  47.  
    open: config.dev.autoOpenBrowser,
  48.  
    overlay: config.dev.errorOverlay
  49.  
    ? { warnings: false, errors: true }
  50.  
    : false,
  51.  
    publicPath: config.dev.assetsPublicPath,
  52.  
    proxy: config.dev.proxyTable,
  53.  
    quiet: true, // necessary for FriendlyErrorsPlugin
  54.  
    watchOptions: {
  55.  
    poll: config.dev.poll,
  56.  
    },
  57.  
    setup(app) {
  58.  
    // 寫個小路由,打開瀏覽器的時候可以選一個開發路徑
  59.  
    let html = `<html><head><title>調試頁面</title>`
  60.  
    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>`
  61.  
    html += `</head><body><div class="module-menu">`
  62.  
    for(let module of moduleList){
  63.  
    html += `<a href="/${module}/index.html" target="container">${module.toString()}</a><br>`
  64.  
    }
  65.  
    html += `</div>`
  66.  
    html += `<div class="module-container"><iframe src="/${moduleList[0]}/index.html" name="container" frameborder="0"></iframe></div>`
  67.  
    html += `</body></html>`
  68.  
    // let sentHref = ''
  69.  
    // for(var module in moduleList){
  70.  
    // sentHref += '<a href="/'+ moduleList[module] +'/index.html">點我調試模塊:'+ moduleList[module].toString() +'</a> <br>'
  71.  
    // }
  72.  
    app.get( '/moduleList', (req, res, next) => {
  73.  
    res.send(html)
  74.  
    })
  75.  
    // 訪問根路徑時重定向到moduleList
  76.  
    app.get( '/', (req, res, next) => {
  77.  
    res.redirect( '/moduleList')
  78.  
    })
  79.  
    }
  80.  
    },
  81.  
    plugins: [
  82.  
    new webpack.DefinePlugin({
  83.  
    'process.env': require('../config/dev.env')
  84.  
    }),
  85.  
    new webpack.HotModuleReplacementPlugin(),
  86.  
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
  87.  
    new webpack.NoEmitOnErrorsPlugin(),
  88.  
    // copy custom static assets
  89.  
    new CopyWebpackPlugin([
  90.  
    {
  91.  
    from: path.resolve(__dirname, '../static'),
  92.  
    to: config.dev.assetsSubDirectory,
  93.  
    ignore: ['.*']
  94.  
    }
  95.  
    ]),
  96.  
    // https://github.com/ampedandwired/html-webpack-plugin
  97.  
    // new HtmlWebpackPlugin({
  98.  
    // filename: 'a/index.html',
  99.  
    // template: './src/modules/a/index.html',
  100.  
    // inject: true,
  101.  
    // chunks: ['a']
  102.  
    // }),
  103.  
    ].concat(htmlWebpackPlugins)
  104.  
    })
  105.  
     
  106.  
    module.exports = new Promise((resolve, reject) => {
  107.  
    portfinder.basePort = process.env.PORT || config.dev.port
  108.  
    portfinder.getPort( (err, port) => {
  109.  
    if (err) {
  110.  
    reject(err)
  111.  
    } else {
  112.  
    // publish the new Port, necessary for e2e tests
  113.  
    process.env.PORT = port
  114.  
    // add port to devServer config
  115.  
    devWebpackConfig.devServer.port = port
  116.  
     
  117.  
    // Add FriendlyErrorsPlugin
  118.  
    devWebpackConfig.plugins.push( new FriendlyErrorsPlugin({
  119.  
    compilationSuccessInfo: {
  120.  
    messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
  121.  
    },
  122.  
    onErrors: config.dev.notifyOnErrors
  123.  
    ? utils.createNotifierCallback()
  124.  
    : undefined
  125.  
    }))
  126.  
     
  127.  
    resolve(devWebpackConfig)
  128.  
    }
  129.  
    })
  130.  
    })

第七步:修改webpack.prod.conf.js的配置,增加對不同打包模式的處理。

  1.  
    'use strict'
  2.  
    const path = require('path')
  3.  
    const utils = require('./utils')
  4.  
    const webpack = require('webpack')
  5.  
    const config = require('../config')
  6.  
    const merge = require('webpack-merge')
  7.  
    const baseWebpackConfig = require('./webpack.base.conf')
  8.  
    const CopyWebpackPlugin = require('copy-webpack-plugin')
  9.  
    const HtmlWebpackPlugin = require('html-webpack-plugin')
  10.  
    const ExtractTextPlugin = require('extract-text-webpack-plugin')
  11.  
    const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
  12.  
    const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
  13.  
     
  14.  
    const env = process.env.NODE_ENV === 'testing'
  15.  
    ? require('../config/test.env')
  16.  
    : require('../config/prod.env')
  17.  
    // 獲取所有模塊列表
  18.  
    const moduleToBuild = require('./module-conf').getModuleToBuild() || []
  19.  
    // 組裝多個(有幾個module就有幾個htmlWebpackPlugin)htmlWebpackPlugin,然后追加到配置中
  20.  
    const htmlWebpackPlugins = []
  21.  
    // 判斷一下是否為分開打包模式
  22.  
    if (process.env.MODE_ENV === 'separate') {
  23.  
    // 分開打包時是通過重復運行指定模塊打包命令實現的,所以每次都是單個html文件,只要配置一個htmlPlugin
  24.  
    htmlWebpackPlugins.push( new HtmlWebpackPlugin({
  25.  
    filename: process.env.NODE_ENV === 'testing'
  26.  
    ? 'index.html'
  27.  
    : config.build.index,
  28.  
    // template: 'index.html',
  29.  
    template: config.build.htmlTemplate,
  30.  
    inject: true,
  31.  
    minify: {
  32.  
    removeComments: true,
  33.  
    collapseWhitespace: true,
  34.  
    removeAttributeQuotes: true
  35.  
    // more options:
  36.  
    // https://github.com/kangax/html-minifier#options-quick-reference
  37.  
    },
  38.  
    // necessary to consistently work with multiple chunks via CommonsChunkPlugin
  39.  
    chunksSortMode: 'dependency'
  40.  
    }))
  41.  
    } else {
  42.  
    // 一起打包時是通過多入口實現的,所以要配置多個htmlPlugin
  43.  
    for (let module of moduleToBuild) {
  44.  
    htmlWebpackPlugins.push( new HtmlWebpackPlugin({
  45.  
    filename: `${module}.html`,
  46.  
    template: `./src/modules/${module}/index.html`,
  47.  
    inject: true,
  48.  
    // 這里要指定把哪些chunks追加到html中,默認會把所有入口的chunks追加到html中,這樣是不行的
  49.  
    chunks: [ 'vendor', 'manifest', module],
  50.  
    // filename: process.env.NODE_ENV === 'testing'
  51.  
    // ? 'index.html'
  52.  
    // : config.build.index,
  53.  
    // template: 'index.html',
  54.  
    minify: {
  55.  
    removeComments: true,
  56.  
    collapseWhitespace: true,
  57.  
    removeAttributeQuotes: true
  58.  
    // more options:
  59.  
    // https://github.com/kangax/html-minifier#options-quick-reference
  60.  
    },
  61.  
    // necessary to consistently work with multiple chunks via CommonsChunkPlugin
  62.  
    chunksSortMode: 'dependency'
  63.  
    }))
  64.  
    }
  65.  
    }
  66.  
     
  67.  
    // 獲取當前打包的目錄名稱
  68.  
    const webpackConfig = merge(baseWebpackConfig, {
  69.  
    module: {
  70.  
    rules: utils.styleLoaders({
  71.  
    sourceMap: config.build.productionSourceMap,
  72.  
    extract: true,
  73.  
    usePostCSS: true
  74.  
    })
  75.  
    },
  76.  
    devtool: config.build.productionSourceMap ? config.build.devtool : false,
  77.  
    output: {
  78.  
    path: config.build.assetsRoot,
  79.  
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
  80.  
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  81.  
    },
  82.  
    plugins: [
  83.  
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
  84.  
    new webpack.DefinePlugin({
  85.  
    'process.env': env
  86.  
    }),
  87.  
    new UglifyJsPlugin({
  88.  
    uglifyOptions: {
  89.  
    compress: {
  90.  
    warnings: false
  91.  
    }
  92.  
    },
  93.  
    sourceMap: config.build.productionSourceMap,
  94.  
    parallel: true
  95.  
    }),
  96.  
    // extract css into its own file
  97.  
    new ExtractTextPlugin({
  98.  
    filename: utils.assetsPath('css/[name].[contenthash].css'),
  99.  
    // Setting the following option to `false` will not extract CSS from codesplit chunks.
  100.  
    // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
  101.  
    // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
  102.  
    // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
  103.  
    allChunks: true,
  104.  
    }),
  105.  
    // Compress extracted CSS. We are using this plugin so that possible
  106.  
    // duplicated CSS from different components can be deduped.
  107.  
    new OptimizeCSSPlugin({
  108.  
    cssProcessorOptions: config.build.productionSourceMap
  109.  
    ? { safe: true, map: { inline: false } }
  110.  
    : { safe: true }
  111.  
    }),
  112.  
    // generate dist index.html with correct asset hash for caching.
  113.  
    // you can customize output by editing /index.html
  114.  
    // see https://github.com/ampedandwired/html-webpack-plugin
  115.  
    /*
  116.  
    new HtmlWebpackPlugin({
  117.  
    filename: process.env.NODE_ENV === 'testing'
  118.  
    ? 'index.html'
  119.  
    : config.build.index,
  120.  
    // template: 'index.html',
  121.  
    template: config.build.htmlTemplate,
  122.  
    inject: true,
  123.  
    minify: {
  124.  
    removeComments: true,
  125.  
    collapseWhitespace: true,
  126.  
    removeAttributeQuotes: true
  127.  
    // more options:
  128.  
    // https://github.com/kangax/html-minifier#options-quick-reference
  129.  
    },
  130.  
    // necessary to consistently work with multiple chunks via CommonsChunkPlugin
  131.  
    chunksSortMode: 'dependency'
  132.  
    }),
  133.  
    */
  134.  
    // keep module.id stable when vendor modules does not change
  135.  
    new webpack.HashedModuleIdsPlugin(),
  136.  
    // enable scope hoisting
  137.  
    new webpack.optimize.ModuleConcatenationPlugin(),
  138.  
    // split vendor js into its own file
  139.  
    new webpack.optimize.CommonsChunkPlugin({
  140.  
    name: 'vendor',
  141.  
    minChunks ( module) {
  142.  
    // any required modules inside node_modules are extracted to vendor
  143.  
    return (
  144.  
    module.resource &&
  145.  
    /\.js$/.test(module.resource) &&
  146.  
    module.resource.indexOf(
  147.  
    path.join(__dirname, '../node_modules')
  148.  
    ) === 0
  149.  
    )
  150.  
    }
  151.  
    }),
  152.  
    // extract webpack runtime and module manifest to its own file in order to
  153.  
    // prevent vendor hash from being updated whenever app bundle is updated
  154.  
    new webpack.optimize.CommonsChunkPlugin({
  155.  
    name: 'manifest',
  156.  
    minChunks: Infinity
  157.  
    }),
  158.  
    // This instance extracts shared chunks from code splitted chunks and bundles them
  159.  
    // in a separate chunk, similar to the vendor chunk
  160.  
    // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
  161.  
    new webpack.optimize.CommonsChunkPlugin({
  162.  
    name: 'app',
  163.  
    async: 'vendor-async',
  164.  
    children: true,
  165.  
    minChunks: 3
  166.  
    }),
  167.  
     
  168.  
    // copy custom static assets
  169.  
    new CopyWebpackPlugin([
  170.  
    {
  171.  
    from: path.resolve(__dirname, '../static'),
  172.  
    to: config.build.assetsSubDirectory,
  173.  
    ignore: ['.*']
  174.  
    }
  175.  
    ])
  176.  
    ].concat(htmlWebpackPlugins)
  177.  
    })
  178.  
     
  179.  
    if (config.build.productionGzip) {
  180.  
    const CompressionWebpackPlugin = require('compression-webpack-plugin')
  181.  
     
  182.  
    webpackConfig.plugins.push(
  183.  
    new CompressionWebpackPlugin({
  184.  
    asset: '[path].gz[query]',
  185.  
    algorithm: 'gzip',
  186.  
    test: new RegExp(
  187.  
    '\\.(' +
  188.  
    config.build.productionGzipExtensions.join( '|') +
  189.  
    ')$'
  190.  
    ),
  191.  
    threshold: 10240,
  192.  
    minRatio: 0.8
  193.  
    })
  194.  
    )
  195.  
    }
  196.  
     
  197.  
    if (config.build.bundleAnalyzerReport) {
  198.  
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  199.  
    webpackConfig.plugins.push( new BundleAnalyzerPlugin())
  200.  
    }
  201.  
     
  202.  
    module.exports = webpackConfig

第八步:修改package.json,增加npm run build-all指令

  1.  
    "scripts": {
  2.  
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
  3.  
    "start": "npm run dev",
  4.  
    "unit": "jest --config test/unit/jest.conf.js --coverage",
  5.  
    "test": "npm run unit",
  6.  
    "lint": "eslint --ext .js,.vue src test/unit",
  7.  
    "build": "node build/build.js",
  8.  
    "build-all": "node build/build-all.js"
  9.  
    },

構建指令

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服務器寫的,跟前端沒有關系,這里大家不要被誤導。

注意事項完。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM