vue中webpack 配置的註釋

什麼是webpack

WebPack可以看做是模塊打包機:它做的事情是,分析你的項目結構,找到JavaScript模塊以及其它的一些瀏覽器不能直接運行的拓展語言(Sass,TypeScript等),並將其轉換和打包爲合適的格式供瀏覽器使用。在3.0出現後,Webpack還肩負起了優化項目的責任。

其最主要的就是三點:打包,轉換,優化

webpack 配置

 module.exports = {
    <!--入口-->
     entry:'',
     <!--出口-->
     output:'',
     <!--模塊-->
     module: {},
     <!--插件-->
     plugins: [],
     <!--服務-->
     devServer: {}
 }
 

這些配置都是老生常淡,直接進入正題吧

webpack 在vue 中

webopack.base.conf.js

'use strict'
//node 模塊
const path = require('path')
// 從vue-loder.conf中引入
const utils = require('./utils')
// 對dev和prod環境配置
const config = require('../config')
//配置css-loader
const vueLoaderConfig = require('./vue-loader.conf')

// 封裝resolve
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 = {
  // context 是webpack entry的上下文,是入口文件所處的目錄的絕對路徑, ../ 對應上層路徑
  context: path.resolve(__dirname, '../'),
  // entry 代表spa入口,從何main.js 引入所有組件
  entry: {
    app: './src/main.js'
  },
  // 輸出路徑
  output: {
    // assetsRoot: path.resolve(__dirname, '../dist'),
    path: config.build.assetsRoot,
    // 代表輸出打包後的名字
    filename: '[name].js',
    // 對應環境  assetsPublicPath: '/', assetsPublicPath: '/', 是dev還是prod
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  // resolve字段告訴webpack怎麼去搜索文件
  resolve: {
    // 默認值:extensions:['.js', '.json'],當導入語句沒帶文件後綴時,Webpack會根據extensions定義的後綴列表進行文件查找
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  // 模塊打包器
  module: {
    rules: [
      // 配置是否開啓 eslint
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        //對css 配置封裝 exports.cssLoaders
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        // babel 引入查找,從src,test,node_modules中
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        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: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

webpack.dev.conf.dev

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
//一個可以合併數組和對象的插件
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
// 用於將static中的靜態文件複製到產品文件夾dist
const CopyWebpackPlugin = require('copy-webpack-plugin')
//用於將webpack編譯打包後的產品文件注入到html模板中,即自動在index.html中裏面機上和標籤引用webpack打包後的文件
const HtmlWebpackPlugin = require('html-webpack-plugin')
//用於更友好的輸出webpack的警告,錯誤信息等
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// 端口累加
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
// 合併base內容到裏面
const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    // exports.styleLoaders
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    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,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    }
  },
  plugins: [
    // Webpack中使用DefinePlugin插件來定義配置文件適用的環境
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    // 開啓模塊熱替換HMR
    new webpack.HotModuleReplacementPlugin(),
    // 使用 NamedModulesPlugin 可以使控制檯打印出被替換的模塊的名稱而非數字ID,另外同webpack監聽,忽略node_modules目錄的文件可以提升性能。
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    // 使用 NoEmitOnErrorsPlugin 來跳過輸出階段,這樣可以確保輸出資源不會包含錯誤
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    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 {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      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)
    }
  })
})

webapck.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')
// 打包html
const HtmlWebpackPlugin = require('html-webpack-plugin')
// extract-text-webpack-plugin該插件的主要是爲了抽離css樣式,防止將樣式打包在js中引起頁面樣式加載錯亂的現象
const ExtractTextPlugin = require('extract-text-webpack-plugin')
//  用於優化或者壓縮CSS資源 
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// 壓縮js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

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

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      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
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      // Setting the following option to `false` will not extract CSS from codesplit chunks.
      // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
      // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, 
      // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
      allChunks: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: config.build.productionSourceMap
        ? { safe: true, map: { inline: false } }
        : { safe: true }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see 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
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    // 該插件會根據模塊的相對路徑生成一個四位數的hash作爲模塊id, 建議用於生產環境
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    //作用域提升,是在Webpack3中推出的功能,它分析模塊間的依賴關係,儘可能將被打散的模塊合併到一個函數中,但不能造成代碼冗餘,所以只有被引用一次的模塊才能被合併。由於需要分析模塊間的依賴關係,所以源碼必須是採用了ES6模塊化的,否則Webpack會降級處理不採用Scope Hoisting。
    new webpack.optimize.ModuleConcatenationPlugin(),
    // split vendor js into its own file
    // 提取頁面間公共代碼,以利用緩存
    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
    }),
    // This instance extracts shared chunks from code splitted chunks and bundles them
    // in a separate chunk, similar to the vendor chunk
    // see: 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
    }),

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  //是否開啓Gzip加速
  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) {
  // 可視化分析工具,比Webapck Analyse更直觀。使用也很簡單
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章