模块化---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>
相关推荐
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
ew452182 小时前
ElementUI表格表头自定义添加checkbox,点击选中样式不生效
前端·javascript·elementui
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
Moon.92 小时前
el-table的hasChildren不生效?子级没数据还显示箭头号?树形数据无法展开和收缩
前端·vue.js·html
垚垚 Securify 前沿站2 小时前
深入了解 AppScan 工具的使用:筑牢 Web 应用安全防线
运维·前端·网络·安全·web安全·系统安全
工业甲酰苯胺5 小时前
Vue3 基础概念与环境搭建
前端·javascript·vue.js
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
柴柴的小记8 小时前
前端vue引入特殊字体不生效
前端·javascript·vue.js
柠檬豆腐脑9 小时前
从前端到全栈:新闻管理系统及多个应用端展示
前端·全栈
bin91539 小时前
DeepSeek 助力 Vue 开发:打造丝滑的颜色选择器(Color Picker)
前端·javascript·vue.js·ecmascript·deepseek