美文网首页
webpack4.0 优化

webpack4.0 优化

作者: 成熟稳重的李先生 | 来源:发表于2019-07-07 18:43 被阅读0次

    1.常用优化项

    • 在匹配规则中添加包含(include)或者不包含(exclude)选项
    {
            test: /\.js$/,
            exclude: /node_modules/,
            include: path.resolve("src"),
            use: {
              loader: "babel-loader",
              options: {
                presets: ["@babel/preset-env"],
                plugins: [
                  ["@babel/plugin-proposal-class-properties"],
                  ["@babel/plugin-transform-runtime"]
                ]
              }
            },
            include: path.resolve("src"),
            exclude: /node_modules/
          }
    
    • 之前提到过的“noParse”字段
    module: {
     npParse: /jquery/  //不去解析jquery的依赖库
    }
    
    • 引入第三包时的优化

    这里我们以moment.js(一个格式化时间的插件)为例

    //index.js
    import moment from "moment";[图片上传中...(164123.png-dcdb54-1562488922729-0)]
    moment.locale('zh-cn');  // 使用中文语言包
    let r = moment()
      .endOf("day")
      .fromNow();
    
    console.log(r);
    

    然后运行打包命令,结果如下:

    164123.png
    可以看到,我们就只写了几行代码,但打包出的js却又1.57兆,这是因为moment默认会包含所有语言包,但我们只需要中文语言包。webpack提拱了一个插件IgnorePlugin来忽略一些内容。
    我们首先要查找引入语言包的位置,看moment源码是如何引入语言包的

    因此我们需要忽略这个“.locale”引用,代码如下:
    //webpack.config.js
    plugins: [
        new webpack.IgnorePlugin(/\.\/local/, /moment/)  //忽略从moment中对 ./locale的引用
     ]
    

    因为忽略了语言包的引入,因此,我们就需要自己手动的引用中文语言包

    //index.js
    import moment from "moment";
    
    // 手动引入所需的语言包
    import 'moment/locale/zh-cn';
    
    moment.locale('zh-cn');  // 使用中文语言包
    let r = moment()
      .endOf("day")
      .fromNow();
    
    console.log(r);
    

    现在打包,看结果:.

    184255.png
    正确的引入了中文包
    值得一提的是,webpack在打包过程中,对待吗默认还做了一些优化,比如tree-shaking(生产环境下剔除无用代码,这个旨在es6的模块导入语法中有体现,即import语法),scope hosting(作用域提升)
    //新建test.js,内容如下:
    let sum = (a, b) => {
      return a + b + "sum";
    };
    
    let minus = (a, b) => {
      return a - b + "minus";
    };
    
    export default {
      sum,
      minus
    };
    // index.js
    import calc from "./test.js";
    
    console.log(calc.add(1, 2));
    

    打包后(生产环境):

    // bundle.js
    !(function(e) {
    ...
    })([
      function(e, t, r) {
        "use strict";
        r.r(t);
        var n = function(e, t) {
          return e + t + "sum";
        };
        console.log(n(1, 2));
      }
    ]); //可以看出,只打包了sum,没有minus(如果在index中引入test.js的方式是require的话,就没有这种优化了,并且会把导出挂在default属性上)
    

    scope hosting

    //index.js
    let a = 1;
    let b = 2;
    let c = 3;
    let d = a+b+c;
    
    console.log(d, '-------------------')
    

    打包后:

    //bundle.js
    !(function(e) {
      ....
    })([
      function(e, t) {
        console.log(6, "-------------------");  // webpack会自动省略一些可以简化的代码
      }
    ]);
    
    

    相关文章

      网友评论

          本文标题:webpack4.0 优化

          本文链接:https://www.haomeiwen.com/subject/zwvvhctx.html