vue-cli腳手架中webpack配置詳解

什麼是webpack

webpack是一個module bundler(模塊打包工具),所謂的模塊就是在平時的前端開發中,用到一些靜態資源,如JavaScript、CSS、圖片等文件,webpack就將這些靜態資源文件稱之爲模塊css

webpack支持AMD和CommonJS,以及其餘的一些模塊系統,而且兼容多種JS書寫規範,能夠處理模塊間的以來關係,因此具備更強大的JS模塊化的功能,它能對靜態資源進行統一的管理以及打包發佈,在官網中用這張圖片介紹:
clipboard.pnghtml

它在不少地方都能替代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

基於本人項目使用

vue webpack的配置文件的基本目錄結構以下:html5

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
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
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
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
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
相關文章
相關標籤/搜索