requirejs基础整理

版权声明:本文为博主原创文章,随便转载,出处注明一哈 https://blog.csdn.net/u012551928/article/details/80026950

一、介绍

1.使用用途

有效的防止文件冲突

声明不同js文件之间的依赖

可以让代码以模块化的方式组织

2.下载及引入

路径:http://www.requirejs.cn/docs/download.html

中文API: http://www.requirejs.cn/home.html

/**

*data-main入口文件

*/

<script data-main="scripts/main" src="scripts/require.js"></script>

3.常用方法

requirejs.config() //定义别名

requirejs //引入模块

define //定义模块

4.简单案例

构建项目结构如下:

|--requireJsTest

|--scripts

         |--common

                  |--util.js

         |--main.js

         |--require.js

|--index.html

文件:index.html

<!DOCTYPE html>

<html>

    <head>

    </head>

    <body>

        <script data-main="scripts/main" src="scripts/require.js"></script>

    </body>

</html>

文件:main.js

//别名

requirejs.config({

    paths:{

        tool:"common/util"

    }

});

//使用别名,引入util.js里面定义的模块

require(["tool"], function(tool) {

    tool.test();

});

文件:util.js

// 定义模块

define([],function(){

    return {

        test:function(){

            alert(1);

        }

    }

});

附视频学习地址:http://haokan.baidu.com/v?pd=wisenatural&vid=14960822007606944695

扩展:插件形式的非AMD规范采用如下形式,”垫”成可用模块。

require.config({

    shim:{

        "underscore":{

            exports :"_";

        }

    }

})

猜你喜欢

转载自blog.csdn.net/u012551928/article/details/80026950