看介绍是很简单的,但是我做这个简单的demo,过程还是很曲折的。引进jquery,老是没引到,后来加上shim好了,再后来,去掉shim也是好的,我崩溃了。。。
二话不说上代码,给初学者看看。因为我在网上没找到一个完整的代码。要是有一个简单的demo就好了。我是看文档一步一步来的。
1、目录结构,
WebRoot
js
config.js
require.js
jquery-3.0.0.min.js
a.js
MyHtml.html
2.文件,
MyHtml.html
<!DOCTYPE html>
<html>
<head>
<title>jQuery+RequireJS Sample Page</title>
</head>
<body>
<h1>jQuery+RequireJS Test Page</h1>
<p>Tests loading of jquery plugins with require.</p>
<script src="js/require.js" data-main="js/a.js"></script>
</body>
</html>
a.js
require(['config'],function(config){
require(['jquery'], function($) {
debugger;
alert($("body").css("background"));
});
});
config.js
require.config({
baseUrl: 'js',
paths: {
// the left side is the module ID,
// the right side is the path to
// the jQuery file, relative to baseUrl.
// Also, the path should NOT include
// the '.js' file extension. This example
// is using jQuery 1.9.0 located at
// js/lib/jquery-1.9.0.js, relative to
// the HTML page.
'jquery': 'jquery-3.0.0.min'
}/*,
shim: {
'jquery': {
exports: '$'
}
}*/
});
简单说一下,
html 里面的 data-main=”js/a.js 指的是入口文件,就是require第一个要引进的文件。
a.js 先引进一些配置文件,然后再引进 jquery。当初不加shim是访问不了jquery的,后面什么也没改就好了,我也搞不懂,而且我确定不是缓存问题。
shim 指的是 加载一些不是 define 定义的js,如
test.js
define(function(){
return {}
);
或者
define([‘jquery’],function($){
return {}
);
然后可以这样使用
require([‘test’],function(){
//do something
);