requirejs 模块化开发中遇到的小问题吓死本宝宝了

来源:互联网 发布:世界艺术鉴赏数据库 编辑:程序博客网 时间:2024/04/29 07:16

最近在写系统的时候,前端加入了requirejs,主要是为了跟随潮流。。。骗你的。

之前偶然听公司前端同事提前模块化开发。我没听说过,后来查了资料,都说是好处一大丢。就是方便快捷复用等等。

大家也都拿requirejs和seajs比较。大概了解了一下。哪里不同?反正我现在忘记了,你也不要告诉我,我不听。


正文开始,在使用过程中。这应该是新手都会遇到的问题吧。

站点上使用了 jquery,还有基于jquery的cookie插件 jquery.cookie,自己还写了一个linglingtang.js模块。


三个js文件:require.js、main.js、jquery.js、jquery.cookie.js、linglingtang.js

不好意思,原来是五个。


于是main,js

/*** @description 初始化全局* @author Yoper* @email 944975166@qq.com* @version 1.0  20160528*/requirejs.config({baseUrl : "Public",    paths : {        jquery         :'js/jquery.min',        jquerycookie  :'js/jquery.cookie',linglingtang  :'js/linglingtang'    }});



基于jquery和jquery.cookie的自己的模块linglingtang,js

/*** @description linglingtang.js 依赖于jquery、jquerycookie的模块* @author Yoper* @email 944975166@qq.com* @version 1.0  20160528*/;define(['jquery','jquerycookie'], function($){return {//设置主题颜色set_theme_color : function(theme_color){$.cookie('theme_color', null); $.cookie('theme_color', theme_color,{expires: 365*2, path: '/'}); //有效期2年window.location.href=document.domain+'?theme_color='+theme_color;//location.reload();},};});

然后我要发功了,引用自己的文件,设置我萌萌大的主题颜色

require(['linglingtang'], function(linglingtang){set_theme_color =function (theme_color){linglingtang.set_theme_color(theme_color);}});


最后就是下面这个样子的,就是这个样子,但是每次加载会报错。“jquery.cookie.js:55 Uncaught ReferenceError: jQuery is not defined”

就是温柔的告诉你,没有jquery哦。

骗子,我明明在异步加载中看到已经加载了,而且,循序居然也是对的。

1.require.js

2.main.js

3.jquery.js

4.linglingtang.js

5.jquery.cookie.js

这是监听到的结果

可是却深深的伤害了我18岁幼小的心灵

生怕自己英文不过关找谷歌翻译了一下

“jquery.cookie.js:55 Uncaught ReferenceError: jQuery is not defined” -> “jquery.cookie.js:55未捕获的ReferenceError:jQuery是没有定义”。

网上也有各种解决办法,都说是依赖、循序相关的。但是尝试很很多也没解决。。。


<!doctype html><html><head><script type="text/javascript" src="./js/require.js"></script><script type="text/javascript" src="./js/main.js"></script></head><body> <script> require(['linglingtang'], function(linglingtang){   set_theme_color =function (theme_color)   {linglingtang.set_theme_color(theme_color);    }});</script></body></html>

经过我一个一个实验,解决办法就是加上shim部分即可。一个依赖,加载jquery.cookie前先加载jquery。

/*** @description 初始化全局* @author Yoper* @email 944975166@qq.com* @version 1.0  20160528*/requirejs.config({baseUrl : "Public",    paths : {        jquery         :'js/jquery.min',        jquerycookie  :'js/jquery.cookie',linglingtang  :'js/linglingtang'    },
shim: {jquerycookie: {            deps: ['jquery']        }    }});

好了。php及前端交流群:201923866、370648191

本宝宝邮箱:944975166@qq.com,本宝宝怨气比较大,慎重加QQ,可能会被本宝宝拒绝哦。






























requirejs 模块化开发









零零糖




0 0
原创粉丝点击