模块化---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>
相关推荐
陈随易17 小时前
Postman 被曝自动往 Claude Code 和 Codex 装插件
前端·后端·程序员
Csvn20 小时前
性能监控
前端
Csvn21 小时前
构建工具
前端
FRing0321 小时前
vue2干货总结3(computed计算属性、watch监听器)
开发语言·前端·vue.js·vue2
kyriewen1 天前
Skills 榜前 10 我全装了:只有 3 个能直接用
前端·javascript·程序员
IT_陈寒1 天前
当Java的hashCode遇上Lombok,我的缓存被全清了
前端·人工智能·后端
工控丫丫1 天前
帆软看板中经常使用的公式函数及经常搭的组合
前端·javascript·数据库
jerrywus1 天前
我用 GPT-6.1-sol 做了台会讲解的 3D 售货机:60 罐饮料,一口没喝上
前端·agent·claude
孟陬1 天前
Foobar 技术周刊#159:当看不懂代码时,如何高效排障调试。脏页陷阱:一条只读查询,写入数 TB 数据。推测解码:大模型加速利器
前端·人工智能·后端
Zhao-Jichao1 天前
AI Prompting for Everyone 课程笔记 - P17 图像生成 Imaging Generation
前端