基于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服务器写的,跟前端没有关系,这里大家不要被误导。

注意事项完。

posted @ 2020-02-05 16:20  front-gl  阅读(9136)  评论(0编辑  收藏  举报