vue-cli在webpack的配置文件探究

咱們在構建一個vue項目的時候是否是一頓操做猛如虎啊?
npm install vue-cli -gphp

vue init webpack vue-democss

npm installhtml

npm run dev
而後稍等一小會兒,我們就能在瀏覽器看到了我們的界面啦前端

實際操做項目裏面我們可能須要修改一些配置項才能知足我們本身項目的需求vue

先看看vue項目初始化的文件目錄結構:html5

├─build 
├─config 
├─dist
├─node_modules
├─src
│ ├─assets
│ ├─components
│ ├─router
│ ├─App.vue
│ ├─main.js
├─static
├─.babelrc
├─.editorconfig
├─.gitignore
├─.postcssrc.js
├─index.html
├─package-lock.json
├─package.json
└─README.md

來看看重要的文件,按我理解的順序來啊:node

1.package.json

項目做爲一個你們庭,每一個文件都各司其職。package.json來制定名單,須要哪些npm包來參與到項目中來,npm install命令根據這個配置文件增減來管理本地的安裝包。webpack

這裏面存放着咱們項目的配置項,好比引入的依賴、項目做者、項目版本、項目編譯啓動的命令(放到script下面的)、還有就是dependencies和devDependencies、node和npm的信息、瀏覽器版本信息等等。ios

這兒說一下這個dependencies和devDependenciesgit

咱們在使用npm install 安裝模塊或插件的時候,有兩種命令把他們寫入到 package.json 文件裏面去,好比:

–save-dev 安裝的 插件,被寫入到 devDependencies 對象裏面去
–save 安裝的 插件 ,被寫入到 dependencies 對象裏面去

package.json 文件裏面的 devDependencies 和 dependencies 對象有什麼區別呢?

devDependencies 裏面的插件只用於開發環境,不用於生產環境
dependencies 是須要發佈到生產環境的。

npm install 會安裝兩個依賴
npm install packagename 只安裝dependencies的依賴
npm install packagename --dev 會安裝devDependencies的依賴

若是你只是單純的使用這個包而不須要進行一些改動測試之類的,只安裝dependencies而不安裝devDependencies。執行:npm install --production

file-loader和url-loader的區別:

以圖片爲例,file-loader可對圖片進行壓縮,可是仍是經過文件路徑進行引入,當http請求增多時會下降頁面性能,而url-loader經過設定limit參數,小於limit字節的圖片會被轉成base64的文件,大於limit字節的將進行圖片壓縮的操做。總而言之,url-loader是file-loader的上層封裝。

二、.postcssrc.js

.postcssrc.js文件實際上是postcss-loader包的一個配置,在webpack的舊版本能夠直接在webpack.config.js中配置,現版本中postcss的文檔示例獨立出.postcssrc.js,裏面寫進去須要使用到的插件。

module.exports = {  
    "plugins": {    
        "postcss-import": {},    
        "postcss-url": {}, 
        "autoprefixer": {}
    }
}

關於這個postcss,去搜一下吧,這玩意兒我估摸着之後確定會成爲繼scss和less後最火的一個css預處理

咳咳,以爲本身英語能過關的去這兒看看 postcss

我們這仍是有中文的,哈哈 postcss

三、 .babelrc

要了解這玩意兒,就內容超級多了,babel在vue項目裏面就是爲了把ES6的語法轉換成ES5,
廢話很少說,我們仍是給連接把,笑哭了 babel官方網站 去這兒直接瞭解這個神奇的東東

四、src內文件

咱們開發的代碼都存放在src目錄下,根據須要咱們一般會再建一些文件夾。好比pages的文件夾,用來存放頁面讓components文件夾專門作好組件的工做;api文件夾,來封裝請求的參數和方法;store文件夾,使用vuex來做爲vue的狀態管理工具,我也常叫它做前端的數據庫等。

assets文件:腳手架自動回放入一個圖片在裏面做爲初始頁面的logo。日常咱們使用的時候會在裏面創建js,css,img,fonts等文件夾,做爲靜態資源調用

components文件夾:用來存放組件,合理地使用組件能夠高效地實現複用等功能,從而更好地開發項目。通常狀況下好比建立頭部組件的時候,咱們會新建一個header的文件夾,而後再新建一個header.vue的文件夾

router文件夾:該文件夾下有一個叫index.js文件,用於實現頁面的路由跳轉。

App.vue:做爲咱們的主組件,可經過使用開放入口讓其餘的頁面組件得以顯示。

main.js:做爲咱們的入口文件,主要做用是初始化vue實例並使用須要的插件,小型項目省略router時可放在該處

五、其餘文件

.editorconfig:編輯器的配置文件

.gitignore:忽略git提交的一個文件,配置以後提交時將不會加載忽略的文件

index.html:頁面入口,通過編譯以後的代碼將插入到這來。

package.lock.json:鎖定安裝時的包的版本號,而且須要上傳到git,以保證其餘人在npm install時你們的依賴能保證一致

README.md:可此填寫項目介紹

node_modules:根據package.json安裝時候生成的的依賴(安裝包)

.eslint相關文件,存放項目的編寫格式規範,例如縮進,末尾分號,單雙引號,對項目開發頗有幫助,特別是大項目,規範全部人的開發,減小代碼規範衝突

config文件夾

├─config 
│ ├─dev.env.js 
│ ├─index.js 
│ ├─prod.env.js

一、config/dev.env.js

config內的文件實際上是服務於build的,大部分是定義一個變量export出去

'use strict'
//採用嚴格模式
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
//webpack-merge提供了一個合併函數,它將數組和合並對象建立一個新對象。
//若是遇到函數,它將執行它們,經過算法運行結果,而後再次將返回的值封裝在函數中.這邊將dev和prod進行合併
module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
})

二、config/prod.env.js

當開發是調取dev.env.js的開發環境配置,發佈時調用prod.env.js的生產環境配置

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

三、config/index.js

'use strict'
const path = require('path')
module.exports = {
  dev: {
    // 開發環境下面的配置
    assetsSubDirectory: 'static',    //子目錄,通常存放css,js,image等文件
    assetsPublicPath: '/',           //根目錄
    proxyTable: {},                  //可利用該屬性解決跨域的問題(axios)
    host: 'localhost',               // 地址
    port: 8080,                      //端口號設置,端口號佔用出現問題可在此處修改
    autoOpenBrowser: false,          //是否在編譯(輸入命令行npm run dev)後打開http://localhost:8080/頁面,之前配置爲true,近些版本改成false,我的偏向習慣自動打開頁面
    errorOverlay: true,              //瀏覽器錯誤提示
    notifyOnErrors: true,            //跨平臺錯誤提示
    poll: false,                     //使用文件系統(file system)獲取文件改動的通知devServer.watchOptions
    devtool: 'cheap-module-eval-source-map',//增長調試,該屬性爲原始源代碼(僅限行)不可在生產環境中使用
    cacheBusting: true,              //使緩存失效
    cssSourceMap: true               //代碼壓縮後進行調bug定位將很是困難,因而引入sourcemap記錄壓縮先後的位置信息記錄,當產生錯誤時直接定位到未壓縮前的位置,將大大的方便咱們調試
    },
    build: {  // 生產環境下面的配置
        index: path.resolve(__dirname, '../dist/index.html'),    //index編譯後生成的位置和名字,根據須要改變後綴,好比index.php
        assetsRoot: path.resolve(__dirname, '../dist'),       //編譯後存放生成環境代碼的位置
        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 
│ ├─build.js 
│ ├─check-versions.js 
│ ├─utils.js 
│ ├─vue-loader.conf.js 
│ ├─webpack.base.conf.js 
│ ├─webpack.dev.conf.js 
│ ├─webpack.prod.conf.js

一、build/build.js

'use strict'
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')
//調用start的方法實現加載動畫,優化用戶體驗
const spinner = ora('building for production...')
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, // 若是您使用的是ts-loader,將其設置爲true將致使在構建期間出現TypeScript錯誤
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    if (stats.hasErrors()) {
      console.log(chalk.red('構建失敗並出現錯誤\n'))
      process.exit(1)
    }

    console.log(chalk.cyan('構建成功.\n'))
    console.log(chalk.yellow(
      'Tip: 構建的文件旨在經過HTTP服務器提供.\n' + '正在打開index.html 在file:// won\'t work.\n'
    ))
  })
})

二、build/check-version.js

該文件用於檢測node和npm的版本,實現版本依賴

'use strict'
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)
  }
}

三、build/utils.js

utils是工具的意思,是一個用來處理css的文件。

'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
//導出文件的位置,根據環境判斷開發環境和生產環境,爲config文件中index.js文件中定義的build.assetsSubDirectory或dev.assetsSubDirectory
exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory
  //Node.js path 模塊提供了一些用於處理文件路徑的小工具
  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
        })
      })
    }

    //ExtractTextPlugin可提取出文本,表明首先使用上面處理的loaders,當未能正確引入時使用vue-style-loader
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } 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')
    })
  }
}
path.posix:提供對路徑方法的POSIX(可移植性操做系統接口)特定實現的訪問,便可跨平臺,區別於win32。
path.join:用於鏈接路徑,會正確使用當前系統的路徑分隔符,Unix系統是"/",Windows系統是""

四、vue-loader.conf.js

該文件的主要做用就是處理.vue文件,解析這個文件中的每一個語言塊(template、script、style),轉換成js可用的js模塊。

'use strict'
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和插件等。

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
//拼接出絕對路徑
  return path.join(__dirname, '..', dir)
}
// 添加eslint過濾
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 = {
  //path.join將路徑片斷進行拼接,而path.resolve將以/開始的路徑片斷做爲根目錄,在此以前的路徑將會被丟棄
  //path.join('/a', '/b') // 'a/b',path.resolve('/a', '/b') // '/b'
  context: path.resolve(__dirname, '../'),
  //配置入口,默認爲單頁面因此只有app一個入口
  entry: {
    app: './src/main.js'
  },
  //配置出口,默認是/dist做爲目標文件夾的路徑
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    //自動的擴展後綴,好比一個js文件,則引用時書寫可不要寫.js
    extensions: ['.js', '.vue', '.json'],
    //建立路徑的別名,好比增長'components': resolve('src/components')等
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  //使用插件配置相應文件的處理方法
  module: {
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),  // 加載eslint代碼規範規則
      //使用vue-loader將vue文件轉化成js的模塊
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      //js文件須要經過babel-loader進行編譯成es5文件以及壓縮等操做
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      //圖片、音像、字體都使用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]')
        }
      }
    ]
  },
//如下選項是Node.js全局變量或模塊,這裏主要是防止webpack注入一些Node.js的東西到vue中
  node: {
    // 防止webpack注入無用的setImmediate polyfill,由於Vue源包含它(雖然只有它是原生的才使用它)
    setImmediate: false,
    // 防止webpack將模擬注入到對客戶端沒有意義的Node本機模塊
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

六、webpack.dev.conf.js

'use strict'
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 path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
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)

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: {
    clientLogLevel: 'warning',    //控制檯顯示的選項有none, error, warning 或者 info
    //當使用 HTML5 History API 時,任意的 404 響應均可能須要被替代爲 index.html
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,    //熱加載
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,    //壓縮
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,    //調試時自動打開瀏覽器
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,    // warning 和 error 都要顯示
    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
    }),
    //複製插件
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']    //忽略.*的文件
      }
    ])
  ]
})

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
      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

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const env = require('../config/prod.env')

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    //調用utils.styleLoaders的方法
    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
    }),
    //抽取文本。好比打包以後的index頁面有style插入,就是這個插件抽取出來的,減小請求
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      // 將如下選項設置爲「false」將不會從codesplit塊中提取CSS
      // 當webpack加載了codesplit塊時,他們的CSS將使用style-loader動態插入
      // 它目前設置爲「true」,由於咱們看到源代碼包含在codesplit包中,當它是「false」增長文件大小時:https://github.com/vuejs-templates/webpack/issues/1110
      allChunks: true,
    }),
    // 壓縮提取的CSS。 咱們正在使用此插件,以即可以減小來自不一樣組件的可能重複的CSS
    new OptimizeCSSPlugin({
      cssProcessorOptions: config.build.productionSourceMap
        ? { safe: true, map: { inline: false } }
        : { safe: true }
    }),
    // 使用正確的資產哈希生成dist index.html以進行緩存.
    // 您能夠經過編輯/index.html來自定義輸出
    // 請參閱https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,    //刪除註釋
        collapseWhitespace: true,    //刪除空格
        removeAttributeQuotes: true    //刪除屬性的引號
        // 更多屬性參見:https://github.com/kangax/html-minifier#options-quick-reference
      },
      // 經過CommonsChunkPlugin持續使用多個塊的必要條件
      chunksSortMode: 'dependency'    //模塊排序,按照咱們須要的順序排序
    }),
    // 當供應商模塊沒有改變時,保持module.id穩定
    new webpack.HashedModuleIdsPlugin(),
    // 啓用域限制
    new webpack.optimize.ModuleConcatenationPlugin(),
    // 將供應商js拆分爲本身的文件
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) {
        // node_modules中的任何須需模塊都將解壓縮到供應商
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // 將webpack運行時和模塊清單提取到其本身的文件中,以防止在更新應用程序包時更新供應商哈希
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    // 此實例從代碼拆分塊中提取共享塊,並將它們捆綁在一個單獨的塊中,相似於供應商塊,請參閱:https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    // 複製自定義靜態資源到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
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

全是代碼,代碼全是項目模塊的東西。估計有好多小夥伴兒看一點點就關了,能看完的,給你比心哦,哈哈哈

能夠參考那本書叫《深刻淺出webpack》

相關文章
相關標籤/搜索