requireJS 简单上手

昨天简单学习了下requireJS和seaJS,两个都是解决模块化开发的问题的工具,使用也有很多相似之处,只是requireJS是AMD规范,seaJS使用的是CMD规范。

目录结构:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script data-main="./js/base.js" src="http://apps.bdimg.com/libs/require.js/2.1.11/require.min.js" ></script>
    <script type="text/javascript">
        require(['index'], function (index) {
            index.foo();
            console.log('Load complete!');
        });
    </script>
</head>
<body>
    <h2>requireJS</h2>
</body>
</html>

第一行script导入requireJS,然后有个data-main属性,这个文件里制定了引用文件相对目录,也有很多可以配置的东西。

base.js

requirejs.config({
    baseUrl: './',
    paths: {
        index: 'index'
    }
});

这样配置了以后,在家在模块的时候就可以按照baseUrl+paths的路径去加载文件了。

这样我们在index.html就可以直接加载index模块了。

index.js

define(function(){
    function foo() {
        console.log(1);
    }
    return {
        foo: foo
    };
});

反悔了一个对象,然后在index.html就可以使用这个对象了,简单上手就是这样!

原文地址:https://www.cnblogs.com/kiscall/p/5280022.html