webpack由浅入深——(webpack优化配置)

webpack系列文章

  1. webpack由浅入深——(webpack基础配置)
  2. webpack由浅入深——(webpack优化配置)
  3. webpack由浅入深——(tapable)
  4. webpack由浅入深——(ast)
  5. webpack由浅入深——(webapck简易版)
  6. webpack由浅入深——(loader实现)
  7. webpack由浅入深——(plugin实现)

开发优化

开发时的优化主要在于减少webpack编译打包的时间

Dllplugin

随着react和vue的火热,现在很多项目都是基于react和vue创建的。以react为例子,写代码的时候毫无疑问会多次引入react和react-dom。

import React,{Component} from 'react';
import ReactDoM,{render} from 'react-dom';
复制代码

这样会存在一个问题,react和reat-dom中的代码基本不会修改,所以用户编写代码修改时,这些代码也会重新编译和打包,这样就很浪费时间,Dllplugin一次编译打包后就会生成一份不变的代码供其他模块引用,节省开发时编译打包的时间。

  • 配置webpack.dll.config.js
const path = require('path');
const webpack = require('webpack');
module.exports ={
  entry: {
    vendor: ['react', 'redux', 'react-router'],
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].dll.js',
    library: '[name]_[hash]'    //提供全局的变量
  },
  plugins: [
    new webpack.DllPlugin({
      path: path.join(__dirname, 'dist', '[name].manifest.json'),
      name: '[name]_[hash]',
    }),
  ],
};
复制代码
  • 配置script
"scripts": {
    "dev": "webpack-dev-server",
    "build": "webpack",
    "dll":"webpack --config webpack.dll.config.js"
  },
复制代码
  • 配置webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname,'dist'),
    filename: 'index_bundle.js',
  },
  plugins: [
    new webpack.DllReferencePlugin({
      context: path.join(__dirname),
      manifest:path.resolve(__dirname,'dist','vendor.manifest.json')
    }),
    new HtmlWebpackPlugin(),
    new AddAssetHtmlPlugin({
      filepath: path.resolve(__dirname,'dist','vendor.manifest.json')
    }),
  ],
};
复制代码

结构会生成这样的页面

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
    <script type="text/javascript" src="vendor-manifest.json"></script>
    <script type="text/javascript" src="index_bundle.js"></script>
  </body>
</html>
复制代码

happyPack

webpack支持多个线程进行同时进行打包,以便提高编译打包的速度,但是需要注意,如果项目比较简单,不要采用这种方式,因为线程时需要cpu的花销的,简单的项目而使用多线程编译打包,不仅不能加快打包的速度,反而会降低打包的速度

const path = require('path');
cosnt HappyPack = require('happypack');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname,'dist'),
    filename: 'index_bundle.js',
  },
  module:{
      rules:[
      {
        test: /\.js$/,
        loader: 'happypack/loader?id=js',
        exclude: /node_modules/,
        include: path.resolve(__dirname,'src')
      },
      {
        test: /\.css$/,
        loader: 'happypack/loader?id=css',
        exclude: /node_modules/,
        include: path.resolve(__dirname,'src')
      }] 
  },
  plugins: [
    new HappyPack({
      id: 'js',
      threadPool: happyThreadPool,
      loaders: [ 'babel-loader' ]
    }),
    new HappyPack({
      id: 'css',
      threadPool: happyThreadPool,
      loaders: [ 'style-loader', 'css-loader', 'less-loader' ]
    })
  ]
}
复制代码

代码优化

代码优化主要在于模块化管理代码,减少不必要的代码

tree-shaking

tree-shaking会将一些没有用到的代码自动删除掉,这是webpack4内部自带的功能,这里有一个前提就是代码必须采用es6的模块方式import,不然没有办法使用tree-shaking

//a.js
export a = ()=>'a';
export b = ()=>'b';
复制代码
//index.js
import {a} from './a'
console.log(a());
复制代码

最后打后的代码会删除掉b

变量提升

webpack会将某些代码进行优化,以更简洁的方式来替代。

//c.js
export default 'kbz'
复制代码
//index.js
import c from './c'
console.log(c); 
//这两行会简化为 var c = 'kbz'
复制代码
const path = require('path');
const ModuleConcatenationPlugin = require('webpack/lib/optimize/ModuleConcatenationPlugin')
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname,'dist'),
    filename: 'index_bundle.js',
  },
  module:{
  },
  plugins: [
    new ModuleConcatenationPlugin()
  ]
}
复制代码

抽离公共代码

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry: {
      //两个模块都引用了c模块和d模块
      pageA:'./src/pageA',  
      pageB:'./src/pageB',
  },
  output: {
    path: path.resolve(__dirname,'dist'),
    filename: '[name].js',
  },
  optimization:{
      splitChunks:{
          cacheGroups:{
              common:{
                chunks:'initial',
                minChunks:2,    //用两个模块以上同时引用的模块才会抽离出来
                minSize:0       //限制大小,太小了没必要抽离
              }
          }
      }
  },
  plugins:[
    new HtmlWebpackPlugin()
  ]
}
复制代码
//pageA.js pageB.js
import './pageC'
import './pageD'
复制代码
//pageC.js
console.log('c')
复制代码
console.log('d')
复制代码

生成的页面

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
    <script type="text/javascript" src="common~pageA~pageB.js"></script>
    <script type="text/javascript" src="pageA.js"></script>
    <script type="text/javascript" src="pageB.js"></script>
  </body>
</html>


作者:梦想攻城狮
链接:https://juejin.im/post/5bd128b56fb9a05ce1729333
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/sinat_17775997/article/details/83477184