模块化---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>
相关推荐
yvvvy11 分钟前
前端性能优化全家桶:从重绘重排到面试连招,一篇搞懂
前端·javascript·面试
1024小神14 分钟前
微信小程序原生wxml中的事件函数
前端
BigTopOne27 分钟前
[kotlin] inline 函数
前端
怪可爱的地球人28 分钟前
typescript-接口
前端
我是ed30 分钟前
# vue实现拖拉拽效果,类似于禅道首页可拖拽排布展示内容(插件-Grid Layout)
前端
东风西巷34 分钟前
微软恶意软件删除工具:官方免费的系统安全防护利器
前端·安全·microsoft·系统安全·软件需求
跟橙姐学代码38 分钟前
手把手教你玩转 multiprocessing,让程序跑得飞起
前端·python·ipython
华仔啊42 分钟前
SpringBoot+MySQL+Vue实现文件共享系统
java·前端·后端
页面仔Dony1 小时前
流式数据获取与展示
前端·javascript
张志鹏PHP全栈1 小时前
postcss-px-to-viewport如何实现单页面使用?
前端