RequireJS与Zepto

之前写过两篇关于RequireJs的博文,今天在做项目的时候遇到了RequireJs中要用到zepto,花了一些时间去探究,说说今天的情况。

刚开始,我认为zepto与jquery是相同的,查询了一些资料也说直接把jquery的路径替换成zepto的路径即可。但是实践过程中,却发现报错了:

1
Uncaught TypeError: e is not a function

点进去查看详情发现,由于代码压缩,e其实是$,也就是说,代码报错的是 $ is not a function

然后我把jquery改成了zepto,依然还是相同的报错。

用google搜了很多资料,有些人说在zepto里面加上一些代码,实践后依然不行。

后来我想到,应该是因为zepto没有按照AMD的规范来写,所以我给zepto设置了shim参数:

1
2
3
4
5
shim: {
'zepto': {
exports: '$'
}
}

大功告成!

这让我更深刻理解exports属性的作用,其实就是这个依赖在使用的时候的变量。在上一次的博文中,我的同事写的代码,我进行了精简,用在了我的新项目中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
require.config({
baseUrl: 'js/vendor/',
paths: {
'js': 'js',
'zepto': 'zepto.1.1.6',
'swiper': 'swiper-3.3.1.jquery.min',
'waypoints': 'zepto.waypoints.min',
'iscroll' : 'iscroll-probe'
},
shim: {
'zepto': {
exports: '$'
},
'waypoints': {
deps: ['zepto'],
exports: 'waypoint'
},
'swiper': {
deps: ['zepto'],
exports: 'Swiper'
},
'iscroll': {
exports: 'IScroll'
}
}
});
require(['zepto', 'waypoints', 'swiper','iscroll'], function($, waypoint, Swiper,IScroll) {
// code here!
});
—— end —— 注:水平有限,难免有误,如有错误欢迎指出!