require.js 基础使用方法记录

require.js作为javsscript的一种模块化编程规范,异步加载模块,主要应用于浏览器端,异步加载js文件,让浏览器不会因为在加载js文件而失去响应。

下载地址:http://www.requirejs.cn/docs/download.html

一、开始

目录结构:

首先要加载require.js

<!-- ***.html-->

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

app.js即是入口文件,我们在里面加载math.js

//app.js
require(['app/math'],function(math){ console.log('1 + 3 = ',math.add(1,3)); })

math.js的编写要符合AMD规范

// math.js
define(function(){
    var add = function(a,b){
        return a+b;
    }
    return {
        add:add
    }
})

(如果有依赖需要加载)

// define的名称要和文件名一致
define('device',['jquery'],function($){ return function(fn) { var _args = [].slice.call(arguments,1); var add = function(){ [].push.apply(_args,[].slice.call(arguments)); return add; }; add.toString = function(){ return fn.apply(null,_args); } return add; } })

这时候运行就可以打印相应的结果

二、加载不符合AMD规范的js文件

require.js为我们提供了一个shim方法,帮助我们加载一些不符合AMD规范的js文件

首先我们随便在People.js里面写点内容:

//People.js
var People = function(name){
    this.name = name;
    this.sayName = function(){
        console.log(`my name is ${this.name}`);
    };
};

改写app.js

//app.js
require.config({
    shim:{
        'app/People':{
            deps:[], // 这里声明依赖文件
            exports:'People' // 输出方法
       } 
    }
});
require(['app/math','app/People'],function(math,People){
    console.log('1 + 3 = ',math.add(1,3));
    var jack = new People('jack');
    jack.sayName();
})

运行,正确输出:

三、baseUrl和paths

require提供一些帮助我们定位文件的方法

在app.js中添加baseUrl:

// app.js
require.config({
    baseUrl:'js/app', //相对于html目录定位
    shim:{
        People:{
            deps:[], // 这里声明依赖文件
            exports:'People' // 输出方法
       } 
    }
});
require(['math','People'],function(math,People){
    console.log('1 + 3 = ',math.add(1,3));
    var jack = new People('jack');
    jack.sayName();
})

同样可以输出相应的结果:

我们还可以为特定的文件指定paths,比如我们要引入jquery:

require.config({
    baseUrl:'js/app', //相对于html目录定位
    paths:{
        jquery:'../lib/jquery' // 相对于baseUrl定位
    },
    shim:{
        People:{
            deps:[], // 这里声明依赖文件
            exports:'People' // 输出方法
        } 
    }
});
require(['math','People','jquery'],function(math,People,$){
    $(function(){
        console.log('1 + 3 = ',math.add(1,3));
        var jack = new People('jack');
        jack.sayName();
    })
})

同样输出了一样的结果:

原文地址:https://www.cnblogs.com/lastnigtic/p/requirejs.html