Js模块化之CMD

时间:2020-05-01

新建项目

在项目根目录初始化

npm init

引入sea.js文件

创建模块

m1.js

define(function (require, exports, module) {
    exports.test = function () {
        console.log('m1 test');
    };
    exports.arr = [1, 2, 3];
});

m2.js

define(function (require,exports,module) {
    console.log('m2');
    // 加载m1模块
    let m1 = require('./m1');
    m1.test();
    console.log(m1.arr);

    // 异步加载
    require.async('./m1',function (m1) {
        console.log('异步加载');
        m1.test();
    });

    module.exports.test = function () {
        console.log('m2 test');
    };
});

主文件

main.js

define(function (require,exports,module) {
    let m1 = require('./m1');
    m1.test();

    let m2 = require('./m2');
    m2.test();
});

测试文件

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="./js/libs/sea.js"></script>
<script>
    seajs.use('./js/src/main.js');
</script>
</body>
</html>