require Js 入门
代码库结构示例:
其中部分文件代码及作用解析如下:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script data-main="js/main.js" src="js/require.js"></script>
</head>
<body>
<p>hi~</p>
</body>
</html>
js/main.js:
js入口文件,其中设置基本参数,调用函数。
require.config({
baseUrl: 'js', /*相对于根路径的绝对路径,与main.js本身的位置没有关系*/
paths: {
jquery: 'jquery/jquery-1.11.1', /*不用加后缀.js*/
aaa: 'jquery/jquery-aaa',
values: 'other_js/values',
tourl: 'other_js/tourl'
}
});
// Start the main logic.
require(['jquery', 'aaa', 'values', 'tourl'], function ($, a, v, t) {
$(document).ready(function () {
t;/*注释后一样执行,因为引用的时候相当于调用了。*/
a.al();/*若想手动调用其中函数,可以设置返回值,然后手动调用*/
});
});
js/other_js/tourl.js:
define(["require"], function(require) {
return alert(require.toUrl("./style.css"));
});
define (function () {
return {
al: function() {alert('kk');}
};
});
执行index.html代码后,结果如图:
第一次弹框:
第二次弹框:
require Js 利用r.js打包 (以下经验借鉴自他人博客点击打开原文链接)
首先下载r,js,然后保证需要打包以及涉及到的文件处于
同一目录下。
代码库结构示例:
其中部分文件代码如下:
index.html