webpack升级2.0遇到的坑

  • 可删除的内容

      DedupePlugin函数被删除了
      
      OccurrenceOrderPlugin函数变成默认引用的,之前引用的也可以删除了
      
      module.preLoaders被取消了
      
      json-loader变成内置了,不需要在单独安装json-loader包
      
  • 语法的改变

    以前省略的用来配置解析各种类型文件的loader,现在不能省略后缀loader,比如babel,现在必须写babel-loader
    
    
    
  • 打包流程的改变

    webpack之前的打包流程是:babel-loader转码 -> webpack打包 -> uglify压缩
       
    webpack2.0的打包流程:webpack打包 -> babel-loader转码 -> uglify压缩
    
    
    
  • webpack2的实现了tree-shaking的原理

      **什么是tree-shaking**?
      
      所谓tree-shaking就是去掉不需要的代码,保留活代码。
      commonjs模块是动态加载的并且可以重命名,在静态分析时要知道哪些代码时不被执行的,需要对数据流进行分析。
      tree-shaking借助es6模块机制。
      通过import/export等关键字来定义输入输出的方法,且其重命名只能通过as这个关键字,
      模块一旦被import进来,就是只读的,这样,我们只根据名字,就可以从入口文件一路溯源到模块定义处,只把用到的方法打包进来。
      

    webpack想要知道哪些代码不需要就的解析es6模块语法,webpack借助acorn(只有解析功能,没有转换功能)实现的,webpack2会统计每个模块export方法被使用的次数,并把没有用到的export删除掉。eg:

    **help.js**
    export function foo() {
        return 'foo';
    }
    export function bar() {
        return 'bar';
    }
    
    
    **main.js**
    import {foo} from './helps';
    
    
    **help.bundle.js 打包之后的help.js的文件**
    function(module, exports, __webpack_require__) {
        /* harmony export */ exports["foo"] = foo;
        /* unused harmony export bar */; 未被使用的模块会被标记成这样
        function foo() {
            return 'foo';
        }
        function bar() {
            return 'bar';
        }
    }
    
    **help.bundle.min.js 压缩之后的help.bundle.js**
    /* 经过压缩后未被使用的 bar模块被删除了 */
    function (t, n, r) {
        function e() {
            return "foo"
        }
        n.foo = e
    }
    

    使用tree-shaking需要设置.bablerc文件中的es2015

    {
       "presets": [
         [
               "es2015", {"modules": false}],
               // webpack understands the native import syntax, and uses it for tree shaking
               "stage-2",
               // Specifies what level of language features to activate.
               // Stage 2 is "draft", 4 is finished, 0 is strawman.
               // See https://tc39.github.io/process-document/
               "react"
               // Transpile React components to JavaScript
         ],
       "plugins": [
           "react-hot-loader/babel"
           // Enables React code to work with HMR.
         ]
       }
    
  • UglifyjsWebpackPlugin插件的修改

      UglifyjsWebpackPlugin插件在代码压缩时候的使用需要手动生命sourceMap的值是true,默认的是false,
      在压缩的时候会生成.map文件(在dll的配置文件中,编译时不生成all.map文件,在dev.config中导致load map文件找不到)
    

    clipboard.png

评论

暂无评论