模块化---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>
相关推荐
共享家95273 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Halo_tjn4 小时前
基于封装的专项 知识点
java·前端·python·算法
m0_748229997 小时前
Vue2 vs Vue3:核心差异全解析
前端·javascript·vue.js
C澒7 小时前
前端监控系统的最佳实践
前端·安全·运维开发
xiaoxue..7 小时前
React 手写实现的 KeepAlive 组件
前端·javascript·react.js·面试
hhy_smile7 小时前
Class in Python
java·前端·python
小邓吖8 小时前
自己做了一个工具网站
前端·分布式·后端·中间件·架构·golang
南风知我意9578 小时前
【前端面试2】基础面试(杂项)
前端·面试·职场和发展
LJianK18 小时前
BUG: Uncaught Error: [DecimalError] Invalid argument: .0
前端
No Silver Bullet9 小时前
Nginx 内存不足对Web 应用的影响分析
运维·前端·nginx