模块化---AMD

  1. main.js文件
javascript 复制代码
require.config({
    'baseUrl': './js',
    'paths': {
        module1:'./modules/module1',
        module2:'./modules/module2',
        // jquery使用小写,因为jquery作为AMD模块,暴露模块使用的键是jquery
        jquery:'./libs/jQuery'
    }
})

// module1和module2的路径,直接映射paths中的路径
// 使用模块
require(['module1'],function(module1) {
    module1.showMsg();
});
require(['module2'],function(module2) {
    module2.showMsg();
});
  1. module1
javascript 复制代码
// 定义模块:不依赖其它模块的情况
define(function(){
    let msg = 'module1';
    const showMsg = function(){
        console.log(msg);
    };
    //  暴露模块
    return {showMsg};
})
  1. module2
javascript 复制代码
// 定义模块:依赖其它模块的情况
define(['jquery'],function($){
    let msg = 'module2';
    const showMsg = function(){
        console.log(msg);
        $('body').css('background','gray');
    };
    //  暴露模块
    return {showMsg};
})
  1. 在index.html使用AMD模块
javascript 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>cmdJS</title>
</head>
<body></body>
<!-- 1.引入require.js,2.data-main定义入口文件 -->
<script data-main = "./js/main.js" src="./js/libs/require.js"></script>
</html>
相关推荐
甜兒.27 分钟前
鸿蒙小技巧
前端·华为·typescript·harmonyos
Jiaberrr4 小时前
前端实战:使用JS和Canvas实现运算图形验证码(uniapp、微信小程序同样可用)
前端·javascript·vue.js·微信小程序·uni-app
everyStudy4 小时前
JS中判断字符串中是否包含指定字符
开发语言·前端·javascript
城南云小白4 小时前
web基础+http协议+httpd详细配置
前端·网络协议·http
前端小趴菜、4 小时前
Web Worker 简单使用
前端
web_learning_3214 小时前
信息收集常用指令
前端·搜索引擎
tabzzz5 小时前
Webpack 概念速通:从入门到掌握构建工具的精髓
前端·webpack
200不是二百5 小时前
Vuex详解
前端·javascript·vue.js
滔滔不绝tao5 小时前
自动化测试常用函数
前端·css·html5
码爸5 小时前
flink doris批量sink
java·前端·flink