webpack4.0高級

環境變量css

webpack --env.NODE_ENV=local --env.production --progress

Tree Shakingnode

  移除JS上下文字未被引用的代碼webpack

  只支持ES6的import和exportgit

optimization: {
  usedExports: true
}
View Code

  package.jsones6

"sideEffects": ["*.css", "*.scss"],
View Code

development and productiongithub

  webpack-mergeweb

  構建開發環境和生成環境typescript

    開發環境須要實時從新加載,熱模塊替換能力的source map和localhost serverjson

    生成環境須要更小的bundle, 更輕量級的source mapapi

Code Splitting

  首先介紹第一種代碼分割

  lodash

  entry: {
    main: resolve(__dirname, '../src/index.js'),
    lodash: resolve(__dirname, '../src/lodash.js')
  }
View Code

建立lodah.js

import _ from 'lodash'

window._ = _
View Code

  webpack的代碼分割

  optimization:{
    splitChunks:{
      chunks: 'all'
    }
  }
View Code

  同步代碼:只須要在webpack.common.js中配置optimization

  異步代碼:經過import,無需任何配置便可,會自動進行代碼分割

async function getLodash() {
  const { default: _ } = await import(/* webpackChunkName: 'lodash' */ 'lodash')
  const ele = document.createElement('div')
  ele.innerHTML = _.join(['Hi', 'Susan'], '*')
  return ele
}

getLodash().then( res => {
  document.body.appendChild(res)
})
View Code

   split-chunks-plugin

 打包分析

  webpack --profile --json > stats.json

   webpack chart

   webpack-bundle-analyzer

filename and chunkFileName

  filename

    對應entry裏面生成的文件名字

  chunFileName  

    chunkFileName未被列在entry中,如異步加載(import)

MiniCssExtractPlugin

  mini-css-extract-plugin

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};
View Code

  development中熱更新

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const devMode = process.env.NODE_ENV !== 'production';

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: devMode ? '[name].css' : '[name].[hash].css',
      chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ],
      },
    ],
  },
};
View Code

  production中css壓縮

const TerserJSPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
  optimization: {
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
};
View Code

緩存

  contenthash

  格式

    [<hashType>:contenthash:<digestType>:<length>]

Shimming

   一直墊片形式,項目中使用lodash,咱們能夠不須要引入lodash,webpack自動完成

    new webpack.ProvidePlugin({
      _: 'lodash'
    })
View Code

index.js代碼,沒引入lodash

const dom = document.createElement('div')
dom.innerHTML = _.join(['Hi', 'Susan'], ' ')
document.body.appendChild(dom)
View Code

  imports-loader

  模塊中的this指向是一個{},能夠是用imports-loader指定this->window

use: 'imports-loader?this=>window'
View Code

TypeScript

  ts-loader  /  typescript

{
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader'
          }
        ]
      }
View Code

  tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist",
    "module": "es6",
    "target": "es5",
    "allowJs": true
  }
}
View Code

   types search

  index.tsx

import * as _ from 'lodash'

class Greeter {
  greeting: string
  constructor(message: string) {
    this.greeting = message
  }
  greet() {
    console.log(_.join([this.greeting, 'Go'], '_'))
  }
}

const greeter = new Greeter('Hi Susan')

greeter.greet()
View Code

devServer 

  historyApiFallback

  proxy

  secure

resolve

  alias

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/')
    }
  }
};
View Code

  extensions

module.exports = {
  //...
  resolve: {
    extensions: ['.wasm', '.mjs', '.js', '.json']
  }
};
View Code
相關文章
相關標籤/搜索