webpack4之高階篇

我欲成風發表於2018-03-25

Tree Shaking

  1. css Tree Shaking
yarn add purify-css purifycss-webpack -D
const glob = require('glob')
const PurifyCSSPlugin = require('purifycss-webpack')
// 去除無用的css
plugins: [
    new PurifyCSSPlugin({
      // 路勁掃描 nodejs內建 路勁檢查
      paths: glob.sync(path.join(__dirname, 'pages/*/*.html'))
    })
]
複製程式碼
  1. js優化
yarn add webpack-parallel-uglify-plugin -D
const WebpackParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')
plugins: [
new WebpackParallelUglifyPlugin({
      uglifyJS: {
        output: {
          beautify: false, //不需要格式化
          comments: false //不保留註釋
        },
        compress: {
          warnings: false, // 在UglifyJs刪除沒有用到的程式碼時不輸出警告
          drop_console: true, // 刪除所有的 `console` 語句,可以相容ie瀏覽器
          collapse_vars: true, // 內嵌定義了但是隻用到一次的變數
          reduce_vars: true // 提取出出現多次但是沒有定義成變數去引用的靜態值
        }
      }
    })
]
複製程式碼

提取公共程式碼

大網站有多個頁面,每個頁面由於採用相同技術棧和樣式程式碼,會包含很多公共程式碼 連結

// webpack4最新配置,可以搜尋關鍵字查查配置項
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          minChunks: 2,
          maxInitialRequests: 5, // The default limit is too small to showcase the effect
          minSize: 0, // This is example is too small to create commons chunks
          name: 'common'
        }
      }
    }
  },
複製程式碼

打包第三方類庫

  1. DllPlugin外掛: 用於打包出一個個動態連線庫
  2. DllReferencePlugin: 在配置檔案中引入DllPlugin外掛打包好的動態連線庫
在package.json中
  "scripts": {
    "build": "webpack --mode development",
    "build:dll": "webpack --config webpack.dll.config.js --mode development",
    "dev": "webpack-dev-server --open --mode development"
  }
新建webpack.dll.config.js  
const path = require('path')
const webpack = require('webpack')

/**
 * 儘量減小搜尋範圍
 * target: '_dll_[name]' 指定匯出變數名字
 */

 module.exports = {
   entry: {
     vendor: ['jquery', 'lodash']
   },
   output: {
     path: path.join(__dirname, 'static'),
     filename: '[name].dll.js',
     library: '_dll_[name]' // 全域性變數名,其他模組會從此變數上獲取裡面模組
   },
   // manifest是描述檔案
   plugins: [
     new webpack.DllPlugin({
       name: '_dll_[name]',
       path: path.join(__dirname, 'manifest.json')
     })
   ]
 }
 
在webpack.config.js中
plugins: [
    new webpack.DllReferencePlugin({
        manifest: path.join(__dirname, 'manifest.json')
    })
]
執行npm run build:dll 就可以打包第三方包了
複製程式碼

使用happypack

HappyPack就能讓Webpack把任務分解給多個子程式去併發的執行,子程式處理完後再把結果傳送給主程式。 happypack

npm i happypack@next -D
const HappyPack = require('happypack')
const os = require('os')
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length })

  {
    test: /\.js$/,
    // loader: 'babel-loader',
    loader: 'happypack/loader?id=happy-babel-js', // 增加新的HappyPack構建loader
    include: [resolve('src')],
    exclude: /node_modules/,
  }
  
  plugins: [
    new HappyPack({
      id: 'happy-babel-js',
      loaders: ['babel-loader?cacheDirectory=true'],
      threadPool: happyThreadPool
    })
]
複製程式碼

顯示打包時間

yarn add progress-bar-webpack-plugin -D
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
plugins: [
    new ProgressBarPlugin({
      format: '  build [:bar] ' + chalk.green.bold(':percent') + ' (:elapsed seconds)'
    })
]
複製程式碼

多頁配置

git完整程式碼連結

  entry: { //entry是一個字串或者陣列都是單頁,是物件則是多頁,這裡是index頁和base頁
    index: './pages/index/index.js',
    base: './pages/base/base.js'
  }
  
  一個頁面對應一個html模板,在plugin中
  plugins: [
    new HtmlWebpackPlugin({
      template: './pages/index/index.html',
      filename: 'pages/index.html',
      hash: true,
      chunks: ['index', 'common'],
      minify: {
        removeAttributeQuotes: true
      }
    }),
    new HtmlWebpackPlugin({
      template: './pages/base/base.html',
      filename: 'pages/base.html',
      hash: true,
      chunks: ['base', 'common'],
      minify: {
        removeAttributeQuotes: true
      }
    }),
  ]
複製程式碼

完整多頁配置程式碼如下 git完整程式碼連結

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
const Webpack = require('webpack')
const glob = require('glob')
const PurifyCSSPlugin = require('purifycss-webpack')

// let cssExtract = new ExtractTextWebpackPlugin('static/css/[name].css')

module.exports = {
  entry: {
    index: './pages/index/index.js',
    base: './pages/base/base.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    // name是entry的名字main,hash是根據打包後的檔案內容計算出來的hash值
    filename: 'static/js/[name].[hash].js',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.css$/, 
        use: ExtractTextWebpackPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'postcss-loader']
        })
      },
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          query: {
            presets: ['env', 'stage-0', 'react'] 
          }
        }
      }
    ]
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          minChunks: 2,
          maxInitialRequests: 5, // The default limit is too small to showcase the effect
          minSize: 0, // This is example is too small to create commons chunks
          name: 'common'
        }
      }
    }
  },
  plugins: [
    new CleanWebpackPlugin([path.join(__dirname, 'dist')]),
    new HtmlWebpackPlugin({
      template: './pages/index/index.html',
      filename: 'pages/index.html',
      hash: true,
      chunks: ['index', 'common'],
      minify: {
        removeAttributeQuotes: true
      }
    }),
    new HtmlWebpackPlugin({
      template: './pages/base/base.html',
      filename: 'pages/base.html',
      hash: true,
      chunks: ['base', 'common'],
      minify: {
        removeAttributeQuotes: true
      }
    }),
    new ExtractTextWebpackPlugin({
      filename: 'static/css/[name].[hash].css'
    }),
    new PurifyCSSPlugin({
      // 路勁掃描 nodejs內建 路勁檢查
      paths: glob.sync(path.join(__dirname, 'pages/*/*.html'))
    })
  ],
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 9090,
    host: 'localhost',
    overlay: true,
    compress: true // 伺服器返回瀏覽器的時候是否啟動gzip壓縮
  }
}

複製程式碼

vue-cli幾個重要路徑

assetsRoot:構建輸出目錄 也就是構建後的東西都扔這裡
assetsSubDirectory:資源子目錄(static) 除了index.html,其餘的js img css都分在這裡
assetsPublicPath:專案目錄 一個槓槓(/) 啥意思呢,是根目錄的意思
複製程式碼

未完待續: 接下來我會基於vue-cli去從新搭建一個工程,單頁,多頁都會有哦!!!讓你看懂vue-cli,並且能夠自定義開發環境!!!

相關文章