欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解vue-cli脚手架中webpack配置方法

程序员文章站 2023-11-23 19:54:52
什么是webpack webpack是一个module bundler(模块打包工具),所谓的模块就是在平时的前端开发中,用到一些静态资源,如javascript、css...

什么是webpack

webpack是一个module bundler(模块打包工具),所谓的模块就是在平时的前端开发中,用到一些静态资源,如javascript、css、图片等文件,webpack就将这些静态资源文件称之为模块

webpack支持amd和commonjs,以及其他的一些模块系统,并且兼容多种js书写规范,可以处理模块间的以来关系,所以具有更强大的js模块化的功能,它能对静态资源进行统一的管理以及打包发布,在官网中用这张图片介绍:

详解vue-cli脚手架中webpack配置方法

它在很多地方都能替代grunt和gulp,因为它能够编译打包css,做css预处理,对js的方言进行编译,打包图片,代码压缩等等。所以在我接触了webpack之后,就不太想用gulp了

为什么使用webpack

总结如下:

  • 对 commonjs 、amd 、es6的语法做了兼容;
  • 对js、css、图片等资源文件都支持打包;
  • 串联式模块加载器以及插件机制,让其具有更好的灵活性和扩展性,例如提供对coffeescript、es6的支持;
  • 有独立的配置文件webpack.config.js;
  • 可以将代码切割成不同的chunk,实现按需加载,降低了初始化时间;
  • 支持 sourceurls 和 sourcemaps,易于调试;
  • 具有强大的plugin接口,大多是内部插件,使用起来比较灵活;
  • webpack 使用异步 io 并具有多级缓存。这使得 webpack 很快且在增量编译上更加快;

webpack主要是用于vue和react较多,其实它就非常像browserify,但是将应用打包为多个文件。如果单页面应用有多个页面,那么用户只从下载对应页面的代码. 当他么访问到另一个页面, 他们不需要重新下载通用的代码。

基于本人项目使用

vue webpack的配置文件的基本目录结构如下:

config
├── dev.env.js //dev环境变量配置
├── index.js // dev和prod环境的一些基本配置
└── prod.env.js // prod环境变量配置
build
├── build.js // npm run build所执行的脚本
├── check-versions.js // 检查npm和node的版本
├── logo.png
├── utils.js // 一些工具方法,主要用于生成cssloader和styleloader配置
├── vue-loader.conf.js // vueloader的配置信息
├── webpack.base.conf.js // dev和prod的公共配置
├── webpack.dev.conf.js // dev环境的配置
└── webpack.prod.conf.js // prod环境的配置

config文件夹下文件详解

dev.env.js

config内的文件其实是服务于build的,大部分是定义一个变量export出去

use strict //[采用严格模式]
/**
* [webpack-merge提供了一个合并函数,它将数组和合并对象创建一个新对象
] 
*/
const merge = require('webpack-merge')
const prodenv = require('./prod.env')

module.exports = merge(prodenv, {
 node_env: '"development"'
})

prod.env.js

当开发时调取dev.env.js的开发环境配置,发布时调用prod.env.js的生产环境配置

use strict
module.exports = {
node_env: '"production"'
}

index.js

const path = require('path')
module.exports = {
 /**
  * [开发环境配置]
  */
dev: {
  assetssubdirectory: 'static', // [子目录,一般存放css,js,image等文件]
assetspublicpath: '/', // [根目录]
/**
* [配置服务代理] 
*/
  proxytable: {
   '/hcm': {
    target: 'https://127.0.0.1:8448',
    changeorigin: true,
    secure: false
   },
   headers: {
    "access-control-allow-origin": "*",
    "access-control-allow-methods": "get, post, put, delete, patch, options",
    "access-control-allow-headers": "x-requested-with, content-type, authorization"
   }
  },
  host: '127.0.0.1', // [浏览器访问地址]
  port: 8083, // [端口号设置,端口号占用出现问题可在此处修改]
  autoopenbrowser: true, // [是否在编译(输入命令行npm run dev)后打开http://127.0.0.1:8083/页面]
  erroroverlay: true, // [浏览器错误提示]
  notifyonerrors: true, // [跨平台错误提示]
  poll:false, // [使用文件系统(file system)获取文件改动的通知devserver.watchoptions] 
  useeslint: true, // [是否启用代码规范检查]
  showeslinterrorsinoverlay: false, // [是否展示eslint的错误提示]
  devtool: 'eval-source-map', // [增加调试,该属性为原始源代码]
  cachebusting: true, // [使缓存失效]
  csssourcemap: false // [代码压缩后进行调bug定位将非常困难,于是引入sourcemap记录压缩前后的位置信息记录,当产生错误时直接定位到未压缩前的位置,将大大的方便我们调试]
 },
/**
* [生产环境配置] 
*/
 build: {
 /**
* [index、login、license、forbidden、notfound、internal.licenses编译后生成的位置和名字,根据需要改变后缀] 
*/
  index: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/meta-inf/resources/index.html'),
  login: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/meta-inf/resources/login.html'),
  license: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/meta-inf/resources/license.html'),
  forbidden: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/meta-inf/resources/error/403.html'),
  notfound: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/meta-inf/resources/error/404.html'),
  internal: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/meta-inf/resources/error/500.html'),
  licenses: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/meta-inf/resources/docs/licenses.html'),
/**
* [编译后存放生成环境代码的位置] 
*/
  assetsroot: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/meta-inf/resources'),
  assetssubdirectory: 'static', //js、css、images存放文件夹名
  assetspublicpath: './', //发布的根目录,通常本地打包dist后打开文件会报错,此处修改为./。如果是上线的文件,可根据文件存放位置进行更改路径
  productionsourcemap: true,
  devtool: '#source-map',
  productiongzip: false, //unit的gzip命令用来压缩文件,gzip模式下需要压缩的文件的扩展名有js和css
  productiongzipextensions: ['js', 'css'],
  bundleanalyzerreport: process.env.npm_config_report //打包分析
 }
}

build文件夹下文件详解

build.js

该文件作用,即构建生产版本。package.json中的scripts的build就是node build/build.js,输入命令行npm run build对该文件进行编译生成生产环境的代码。

require('./check-versions')() //check-versions:调用检查版本的文件。加()代表直接调用该函数
process.env.node_env = 'production' //设置当前是生产环境
/**
*下面定义常量引入插件
*/
const ora = require('ora') //加载动画
const rm = require('rimraf') //删除文件
const path = require('path')
const chalk = require('chalk') //对文案输出的一个彩色设置
const webpack = require('webpack')
const config = require('../config') //默认读取下面的index.js文件
const webpackconfig = require('./webpack.prod.conf')
const spinner = ora('building for production...') //调用start的方法实现加载动画,优化用户体验
spinner.start()
//先删除dist文件再生成新文件,因为有时候会使用hash来命名,删除整个文件可避免冗余
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,
   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'
  ))
 })
})

check-versions.js

该文件用于检测node和npm的版本,实现版本依赖

const chalk = require('chalk') 
const semver = require('semver') //对版本进行检查
const packageconfig = require('../package.json')
const shell = require('shelljs')
function exec (cmd) {
 //返回通过child_process模块的新建子进程,执行 unix 系统命令后转成没有空格的字符串
 return require('child_process').execsync(cmd).tostring().trim()
}
const versionrequirements = [
 {
  name: 'node',
  currentversion: semver.clean(process.version), //使用semver格式化版本
  versionrequirement: packageconfig.engines.node //获取package.json中设置的node版本
 }
]
if (shell.which('npm')) {
 versionrequirements.push({
  name: 'npm',
  currentversion: exec('npm --version'), // 自动调用npm --version命令,并且把参数返回给exec函数,从而获取纯净的版本号
  versionrequirement: packageconfig.engines.npm
 })
}
module.exports = function () {
 const warnings = []
 for (let i = 0; i < versionrequirements.length; i++) {
  const mod = versionrequirements[i]
  if (!semver.satisfies(mod.currentversion, mod.versionrequirement)) {
   //上面这个判断就是如果版本号不符合package.json文件中指定的版本号,就执行下面错误提示的代码
warnings.push(mod.name + ': ' +
    chalk.red(mod.currentversion) + ' should be ' +
    chalk.green(mod.versionrequirement)
   )
  }
 }
 if (warnings.length) {
  console.log('')
  console.log(chalk.yellow('to use this template, you must update following to modules:'))
  console.log()
  for (let i = 0; i < warnings.length; i++) {
   const warning = warnings[i]
   console.log(' ' + warning)
  }
  console.log()
  process.exit(1)
 }
}

utils.js

utils是工具的意思,是一个用来处理css的文件。

const path = require('path')
const config = require('../config')
const extracttextplugin = require('extract-text-webpack-plugin')
const packageconfig = require('../package.json')
exports.assetspath = function (_path) {
 const assetssubdirectory = process.env.node_env === 'production'
  ? config.build.assetssubdirectory
  : config.dev.assetssubdirectory
 return path.posix.join(assetssubdirectory, _path)
}
exports.cssloaders = function (options) {
 options = options || {}
//使用了css-loader和postcssloader,通过options.usepostcss属性来判断是否使用postcssloader中压缩等方法

 const cssloader = {
  loader: 'css-loader',
  options: {
   sourcemap: options.sourcemap
  }
 }
 const postcssloader = {
  loader: 'postcss-loader',
  options: {
   sourcemap: options.sourcemap
  }
 }
 // generate loader string to be used with extract text plugin
 function generateloaders (loader, loaderoptions) {
  const loaders = options.usepostcss ? [cssloader, postcssloader] : [cssloader]
  if (loader) {
   loaders.push({
    loader: loader + '-loader',
  //object.assign是es6语法的浅复制,后两者合并后复制完成赋值
    options: object.assign({}, loaderoptions, {
     sourcemap: options.sourcemap
    })
   })
  }
  // extract css when that option is specified
  // (which is the case during production build)
if (options.extract) {
//extracttextplugin可提取出文本,代表首先使用上面处理的loaders,当未能正确引入时使用vue-style-loader
   return extracttextplugin.extract({
    use: loaders,
    fallback: 'vue-style-loader',
    publicpath: '../../'
   })
} else {
//返回vue-style-loader连接loaders的最终值
   return ['vue-style-loader'].concat(loaders)
  }
 }
 // https://vue-loader.vuejs.org/en/configurations/extract-css.html
 return {
  css: generateloaders(),//需要css-loader 和 vue-style-loader
  postcss: generateloaders(),//需要css-loader和postcssloader 和 vue-style-loader
  less: generateloaders('less'), //需要less-loader 和 vue-style-loader
  sass: generateloaders('sass', { indentedsyntax: true }), //需要sass-loader 和 vue-style-loader
  scss: generateloaders('sass'), //需要sass-loader 和 vue-style-loader
  stylus: generateloaders('stylus'), //需要stylus-loader 和 vue-style-loader
  styl: generateloaders('stylus') //需要stylus-loader 和 vue-style-loader
 }
}
// generate loaders for standalone style files (outside of .vue)
exports.styleloaders = function (options) {
 const output = []
 const loaders = exports.cssloaders(options)
//将各种css,less,sass等综合在一起得出结果输出output
 for (const extension in loaders) {
  const loader = loaders[extension]
  output.push({
   test: new regexp('\\.' + extension + '$'),
   use: loader
  })
 }
 return output
}
exports.createnotifiercallback = () => {
//发送跨平台通知系统
 const notifier = require('node-notifier')
 return (severity, errors) => {
if (severity !== 'error') return
//当报错时输出错误信息的标题,错误信息详情,副标题以及图标
  const error = errors[0]
  const filename = error.file && error.file.split('!').pop()
  notifier.notify({
   title: packageconfig.name,
   message: severity + ': ' + error.name,
   subtitle: filename || '',
   icon: path.join(__dirname, 'logo.png')
  })
 }
}

vue-loader.conf.js

该文件的主要作用就是处理.vue文件,解析这个文件中的每个语言块(template、script、style),转换成js可用的js模块。

const utils = require('./utils')
const config = require('../config')
const isproduction = process.env.node_env === 'production'
const sourcemapenabled = isproduction
 ? config.build.productionsourcemap
 : config.dev.csssourcemap
//处理项目中的css文件,生产环境和测试环境默认是打开sourcemap,而extract中的提取样式到单独文件只有在生产环境中才需要
module.exports = {
 loaders: utils.cssloaders({
  sourcemap: sourcemapenabled,
  extract: isproduction
 }),
 csssourcemap: sourcemapenabled,
 cachebusting: config.dev.cachebusting,
// 在模版编译过程中,编译器可以将某些属性,如 src 路径,转换为require调用,以便目标资源可以由 webpack 处理
 transformtorequire: {
  video: ['src', 'poster'],
  source: 'src',
  img: 'src',
  image: 'xlink:href'
 }
}

webpack.base.conf.js

webpack.base.conf.js是开发和生产共同使用提出来的基础配置文件,主要实现配制入口,配置输出环境,配置模块resolve和插件等

const path = require('path')
const utils = require('./utils')
/**
* [引入index.js文件路径] 
*/
const config = require('../config')
const vueloaderconfig = require('./vue-loader.conf')

/**
 * [获取文件路径]
 * @param dir [文件名称]
 *_dirname为当前模块文件所在目录的绝对路径* 
 *@return 文件绝对路径
*/
function resolve (dir) {
 return path.join(__dirname, '..', dir)
}
const createlintingrule = () => ({
 test: /\.(js|vue)$/,
 loader: 'eslint-loader',
 enforce: 'pre',
 include: [resolve('src'), resolve('test')],
 options: {
  formatter: require('eslint-friendly-formatter'),
  emitwarning: !config.dev.showeslinterrorsinoverlay
 }
})

module.exports = {
 context: path.resolve(__dirname, '../'),
  /**
    * [入口文件配置]
   */
 entry: {
/**
    * [入口文件路径, babel-polyfill是对es6语法的支持]
   */
  app: ['babel-polyfill', './src/main.js'],
  login: ['babel-polyfill', './src/loginmain.js'],
  license: ['babel-polyfill', './src/licensemain.js']
 },
/**
  * [文件导出配置]
*/
 output: {
  path: config.build.assetsroot,
  filename: '[name].js',
  publicpath: process.env.node_env === 'production'
   ? config.build.assetspublicpath
   : config.dev.assetspublicpath //公共存放路径
 },
 resolve: {
  /**
    * [extensions: 配置文件的扩展名,当在important文件时,不用需要添加扩展名]
   */
extensions: ['.js', '.vue', '.json'],
/**
    * [alias 给路径定义别名]
*/
  alias: {
   'vue$': 'vue/dist/vue.esm.js',
   '@': resolve('src')
  }
 },
/**
*使用插件配置相应文件的处理方法
*/
 module: {
rules: [
   ...(config.dev.useeslint ? [createlintingrule()] : []),
/**
   * [使用vue-loader将vue文件转化成js的模块]
*/
   {
    test: /\.vue$/,
    loader: 'vue-loader',
    options: vueloaderconfig
   },
/**
    * [通过babel-loader将js进行编译成es5/es6 文件]
*/
   {
    test: /\.js$/,
    loader: 'babel-loader',
    include: [resolve('src'), resolve('test')]
   },
/**
   * [图片、音像、字体都使用url-loader进行处理,超过10000会编译成base64]
*/
   {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    options: {
     limit: 10000,
     name: utils.assetspath('img/[name].[hash:7].[ext]')
    }
   },
   {
    test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
    loader: 'url-loader',
    options: {
     limit: 10000,
     name: utils.assetspath('media/[name].[hash:7].[ext]')
    }
   },
   {
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
    loader: 'url-loader',
    options: {
     limit: 10000,
     name: utils.assetspath('fonts/[name].[hash:7].[ext]')
    }
   },
/**
    * [canvas 解析]
*/
   {
    test: path.resolve(`${resolve('src')}/lib/jtopo.js`),
    loader: ['exports-loader?window.jtopo', 'script-loader']
   }
  ]
 },
//以下选项是node.js全局变量或模块,这里主要是防止webpack注入一些node.js的东西到vue中 
 node: {
  setimmediate: false,
  dgram: 'empty',
  fs: 'empty',
  net: 'empty',                           
  tls: 'empty',
  child_process: 'empty'
 }
}

webpack.dev.conf.js

const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
//通过webpack-merge实现webpack.dev.conf.js对wepack.base.config.js的继承
const merge = require('webpack-merge')
const basewebpackconfig = require('./webpack.base.conf')
const htmlwebpackplugin = require('html-webpack-plugin')
//美化webpack的错误信息和日志的插件
const friendlyerrorsplugin = require('friendly-errors-webpack-plugin')
// 查看空闲端口位置,默认情况下搜索8000这个端口
const portfinder = require('portfinder')
// processs为node的一个全局对象获取当前程序的环境变量,即host
const host = process.env.host
const port = process.env.port && number(process.env.port)
function resolveapp(relativepath) {
 return path.resolve(relativepath);
}
const devwebpackconfig = merge(basewebpackconfig, {
 module: {
//规则是工具utils中处理出来的styleloaders,生成了css,less,postcss等规则
  rules: utils.styleloaders({ sourcemap: config.dev.csssourcemap, usepostcss: true })
 },
// 增强调试
 devtool: config.dev.devtool,
// 此处的配置都是在config的index.js中设定好了
 devserver: {
//控制台显示的选项有none, error, warning 或者 info
clientloglevel: 'warning',
//使用 html5 history api
historyapifallback: true,
hot: true, //热加载
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, //控制台是否禁止打印警告和错误,若用friendlyerrorsplugin 此处为 true  watchoptions: {
   poll: config.dev.poll, // 文件系统检测改动
  }
 },
 plugins: [
  new webpack.defineplugin({
   'process.env': require('../config/dev.env')
  }),
new webpack.hotmodulereplacementplugin(),//模块热替换插件,修改模块时不需要刷新页面
new webpack.namedmodulesplugin(), // 显示文件的正确名字
new webpack.noemitonerrorsplugin(), //当webpack编译错误的时候,来中端打包进程,防止错误代码打包到文件中
// https://github.com/ampedandwired/html-webpack-plugin
// 该插件可自动生成一个 html5 文件或使用模板文件将编译好的代码注入进去 
new htmlwebpackplugin({
   filename: 'index.html',
   template: 'index.html',
   inject: true,
   chunks: ['app']
  }),
  new htmlwebpackplugin({
   filename: 'login.html',
   template: 'login.html',
   inject: true,
   chunks: ['login']
  }),
  new htmlwebpackplugin({
   filename: 'license.html',
   template: 'license.html',
   inject: true,
   chunks: ['license']
  }),
  new htmlwebpackplugin({
   filename: 'licenses.html',
   template: 'licenses.html',
   inject: true,
   chunks: []
  }),
  new htmlwebpackplugin({
   filename: '404.html',
   template: path.resolve(__dirname, '../errors/404.html'),
   favicon: resolveapp('favicon.ico'),
   inject: true,
   chunks: []
  }),
  new htmlwebpackplugin({
   filename: '403.html',
   template: path.resolve(__dirname, '../errors/403.html'),
   favicon: resolveapp('favicon.ico'),
   inject: true,
   chunks: []
  }),
  new htmlwebpackplugin({
   filename: '500.html',
   template: path.resolve(__dirname, '../errors/500.html'),
   favicon: resolveapp('favicon.ico'),
   inject: true,
   chunks: []
  })
 ]
})

module.exports = new promise((resolve, reject) => {
 portfinder.baseport = process.env.port || config.dev.port
//查找端口号
 portfinder.getport((err, port) => {
  if (err) {
   reject(err)
} else {
//端口被占用时就重新设置evn和devserver的端口
   process.env.port = port
   // add port to devserver config
   devwebpackconfig.devserver.port = port
//友好地输出信息
   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 = require('../config/prod.env')
function resolveapp(relativepath) {
 return path.resolve(relativepath);
}
const webpackconfig = merge(basewebpackconfig, {
 module: {
  rules: utils.styleloaders({
   sourcemap: config.build.productionsourcemap,//开启调试的模式。默认为true
   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 //警告:true保留警告,false不保留
    }
   },
   sourcemap: config.build.productionsourcemap,
   parallel: true
  }),
// extract css into its own file
//抽取文本。比如打包之后的index页面有style插入,就是这个插件抽取出来的,减少请求
new extracttextplugin({
   filename: utils.assetspath('css/[name].[contenthash].css'),
   allchunks: true,
}),
//优化css的插件
  new optimizecssplugin({
   cssprocessoroptions: config.build.productionsourcemap
    ? { safe: true, map: { inline: false } }
    : { safe: true }
  }),
  //html打包
  new htmlwebpackplugin({
   filename: config.build.index,
   template: 'index.html',
   inject: true,
//压缩
   minify: {
    removecomments: true, //删除注释
    collapsewhitespace: true, //删除空格
    removeattributequotes: true //删除属性的引号
   },
   chunks: ['vendor', 'manifest', 'app'],
   // necessary to consistently work with multiple chunks via commonschunkplugin
   chunkssortmode: 'dependency'
  }),
  new htmlwebpackplugin({
   filename: config.build.login,
   template: 'login.html',
   inject: true,
   minify: {
    removecomments: true,
    collapsewhitespace: true,
    removeattributequotes: true
   },
   chunks: ['vendor', 'manifest', 'login'],
   // necessary to consistently work with multiple chunks via commonschunkplugin
   chunkssortmode: 'dependency'
  }),
  new htmlwebpackplugin({
   filename: config.build.license,
   template: 'license.html',
   inject: true,
   minify: {
    removecomments: true,
    collapsewhitespace: true,
    removeattributequotes: true
   },
   chunks: ['vendor', 'manifest', 'license'],
   // necessary to consistently work with multiple chunks via commonschunkplugin
   chunkssortmode: 'dependency'
  }),
  new htmlwebpackplugin({
   filename: config.build.notfound,
   template: path.resolve(__dirname, '../errors/404.html'),
   inject: true,
   favicon: resolveapp('favicon.ico'),
   minify: {
    removecomments: true,
    collapsewhitespace: true,
    removeattributequotes: true
   },
   chunks: [],
   // necessary to consistently work with multiple chunks via commonschunkplugin
   chunkssortmode: 'dependency'
  }),
  new htmlwebpackplugin({
   filename: config.build.forbidden,
   template: path.resolve(__dirname, '../errors/403.html'),
   inject: true,
   favicon: resolveapp('favicon.ico'),
   minify: {
    removecomments: true,
    collapsewhitespace: true,
    removeattributequotes: true
   },
   chunks: [],
   // necessary to consistently work with multiple chunks via commonschunkplugin
   chunkssortmode: 'dependency'
  }),
  new htmlwebpackplugin({
   filename: config.build.internal,
   template: path.resolve(__dirname, '../errors/500.html'),
   inject: true,
   favicon: resolveapp('favicon.ico'),
   minify: {
    removecomments: true,
    collapsewhitespace: true,
    removeattributequotes: true
   },
   chunks: [],
   // necessary to consistently work with multiple chunks via commonschunkplugin
   chunkssortmode: 'dependency'
  }),
  new htmlwebpackplugin({
   filename: config.build.licenses,
   template: 'licenses.html',
   inject: true,
   minify: {
    removecomments: true,
    collapsewhitespace: true,
    removeattributequotes: true
   },
   chunks: [],
   // necessary to consistently work with multiple chunks via commonschunkplugin
   chunkssortmode: 'dependency'
  }),
  // keep module.id stable when vender modules does not change
  new webpack.hashedmoduleidsplugin(),
  // enable scope hoisting
new webpack.optimize.moduleconcatenationplugin(),
//抽取公共的模块, 提升你的代码在浏览器中的执行速度。
  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
}),
// 预编译所有模块到一个闭包中, 
 new webpack.optimize.commonschunkplugin({
   name: 'app',
   async: 'vendor-async',
   children: true,
   minchunks: 3
  }),
//复制,比如打包完之后需要把打包的文件复制到dist里面
  new copywebpackplugin([
   {
    from: path.resolve(__dirname, '../static'),
    to: config.build.assetssubdirectory,
    ignore: ['.*']
   }
  ])
 ]
})

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
  })
 )
}
// 提供带 content-encoding 编码的压缩版的资源
if (config.build.bundleanalyzerreport) {
 const bundleanalyzerplugin = require('webpack-bundle-analyzer').bundleanalyzerplugin
 webpackconfig.plugins.push(new bundleanalyzerplugin())
}
module.exports = webpackconfig

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。