谈谈webpack 的优势


其优势主要可以归类为如下几个:

1. webpack 是以 commonJS 的形式来书写脚本滴,但对 AMD/CMD 的支持也很全面,方便旧项目进行代码迁移。

2. 能被模块化的不仅仅是 JS 了。

3. 开发便捷,能替代部分 grunt/gulp 的工作,比如打包、压缩混淆、图片转base64等。

4. 扩展性强,插件机制完善,特别是支持 React 热插拔(见 react-hot-loader )的功能让人眼前一亮。

我们谈谈第一点。以 AMD/CMD 模式来说,鉴于模块是异步加载的,所以我们常规需要使用 define 函数来帮我们搞回调:

1
2
3
4
5
6
7
8
define([ 'package/lib' ], function (lib){
     function foo(){
         lib.log( 'hello world!' );
     }
     return {
         foo: foo
     };
});

另外为了可以兼容 commonJS 的写法,我们也可以将 define 这么写:

1
2
3
4
5
6
7
8
9
10
11
12
define( function (require, exports, module){
     var someModule = require( "someModule" );
     var anotherModule = require( "anotherModule" );   
 
     someModule.doTehAwesome();
     anotherModule.doMoarAwesome();
 
     exports.asplode = function (){
         someModule.doTehAwesome();
         anotherModule.doMoarAwesome();
     };
});

然而对 webpack 来说,我们可以直接在上面书写 commonJS 形式的语法,无须任何 define (毕竟最终模块都打包在一起,webpack 也会最终自动加上自己的加载器):

1
2
3
4
5
6
7
8
9
10
var someModule = require( "someModule" );
     var anotherModule = require( "anotherModule" );   
 
     someModule.doTehAwesome();
     anotherModule.doMoarAwesome();
 
     exports.asplode = function (){
         someModule.doTehAwesome();
         anotherModule.doMoarAwesome();
  };

这样撸码自然更简单,跟回调神马的说 byebye~

不过即使你保留了之前 define 的写法也是可以滴,毕竟 webpack 的兼容性相当出色,方便你旧项目的模块直接迁移过来。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM