JavaScript 模块化详解

2022-04-15 0 737
目录
  • 前言:
    • 1.概念
    • 2.模块化的好处
    • 3.引入多个script标签后出现的问题
  • 一、CommonJS
    • 二、AMD
      • 三、CMD
        • 四、ES6模块化

          前言:

          1.概念

          • 将一个复杂的程序依据一定的规则(规范)封装成几个块(文件), 并进行组合在一起;
          • 块的内部数据与实现是私有的, 只是向外部暴露一些接口(方法)与外部其它模块通信。

          2.模块化的好处

          • 避免命名冲突(减少命名空间污染);
          • 更好的分离, 按需加载;
          • 更高复用性;
          • 更高可维护性。

          3.引入多个script标签后出现的问题

          • 请求过多(依赖的模块过多,请求就会过多);
          • 依赖模糊(不知道模块的具体依赖关系,导致加载顺序出错);
          • 难以维护(以上两个原因就会造成这个结果)。
          //index.html
          <!DOCTYPE html>
          <html lang="en">
          <head>
            <meta charset="UTF-8">
            <title>Title</title>
            <script src="jQuery.js"></script>
            <script src="module.js"></script>
          </head>
          <body>
            <div>123</div>
          </body>
          <script>
            myModule.foo();
            myModule.bar();
            console.log(myModule.data) ;
            myModule.data = 'xxxx';
            myModule.foo();
          </script>
          </html>
          
          
          
          //module.js IIFE(匿名函数自调用)
          ;(function(window,$){
            let data = "www.baidu.com";
            function foo() {
              console.log(`foo() ${data}`);
              //这里需要使用jQuery库
              $('body').css('background', 'red')
            }
            function bar() {
              console.log(`bar() ${data}`);
              otherFun();
            }
            function otherFun() {
              console.log(`otherFun()`);
            }
            window.myModule = { foo, bar };
          })(window, jQuery)
          
          
          

          一、CommonJS

          • NODE 就是基于commonJS模块规范,每一个文件就是一个模块;有自己的作用域;在服务器端,模块的加载是同步的;在浏览器端,模块需提前编译打包处理

          特点:

          • 所有代码都运行在模块作用域,不会污染全局作用域;
          • 模块可以多次加载,但是只会在第一次加载时运行一次,然后运行结果就被缓存了,以后再加载,就直接读取缓存结果。要想让模块再次运行,必须清除缓存。
          • 模块加载的顺序,按照其在代码中出现的顺序。

          语法:

          • 暴露模块:js module.exports = value 或者 js exports.xxx = value
          • 引入模块:js require('xxx') 如果是第三方模块,xxx为模块名;如果是自定义模块,xxx为模块文件路径

          CommonJS规范规定,每个模块内部,module变量代表当前模块。这个变量是一个对象,它的exports属性(即module.exports)是对外的接口。加载某个模块,其实是加载该模块的module.exports属性。

          require命令用于加载模块文件。require命令的基本功能是,读入并执行一个JavaScript文件,然后返回该模块的exports对象。如果没有发现指定模块,会报错。

          CommonJS模块的加载机制是,输入的是被输出的值的拷贝。也就是说,一旦输出一个值,模块内部的变化就影响不到这个值

          二、AMD

          • 相比于CommonJS的同步加载模块,AMD更适合于浏览器端的非同步模块加载,因为AMD允许指定回调函数
          • 目录结构

          JavaScript 模块化详解

          使用require.js

          <!-- index.html -->
          <script src="https://cdn.bootcdn.net/ajax/libs/require.js/2.3.6/require.js"></script>
          
          
          
          //定义一个没有依赖的module1模块
          define('module1', () => {
            let count = 0;
            const add = () => ++ count;
            const reset = () => count = 0;
            const upperCase = string => string.toUpperCase()
          
            return {
              add,
              reset,
              upperCase
            }
          })
          
          
          
          //定义一个有依赖的module2模块,依赖module1
          define('module2',['module1'], (module1) => {
            const showMsg = () => module1.upperCase('hello-amd');
          
            return {
              showMsg
            }
          })
          
          
          
          <!-- 在html文件中使用模块 -->
          <body>
          
          <script>
            require.config({
              paths: {
                module1: './modules/module1',
                module2: './modules/module2'
              }
            })
            require(['module1', 'module2'], (module1, module2) => {
              console.log(module1.add()) // 1
              console.log(module1.reset()) //0
              console.log(module2.showMsg()) //HELLO-AMD
            })
          </script>
          </body>
          
          
          

          三、CMD

          • CMD集CommonJS与AMD的优点于一身,cmd 规范专门用于浏览器端,模块的加载是异步的,模块使用时才会加载执行(实现了按需加载,而AMD是不支持按需加载的)
          • 目录结构

          JavaScript 模块化详解

          使用sea.js

          <script src="https://cdn.bootcdn.net/ajax/libs/seajs/3.0.3/sea.js"></script>
          
          
          
          //定义模块module1
          define((require, exports, module) => {
          
            let string = 'I am a string';
            const readString = () => 'module1 show() ' + string;
          
            //向外暴露
            exports.readString = readString;
          })
          
          
          
          //定义模块module2
          define((require, exports, module) => {
            exports.msg = "正是在下啊"
          })
          
          
          
          //定义模块module
          define((require, exports, module) => {
            //引入依赖模块(同步)
            var module1 = require('./module1');
            console.log(module1.readString()) // module1 show() I am a string
          
            //引入依赖模块(异步)
            require.async('./module2', md2 => {
              console.log(`这是异步引入的:${md2.msg}`) //这是异步引入的:正是在下啊
            })
          })
          
          
          
          <!-- html文件使用module -->
          <body>
          <script>
            seajs.use('./modules/module')
          </script>
          
          
          

          四、ES6模块化

          ES6 模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。CommonJS 和 AMD 模块,都只能在运行时确定这些东西。
          两个关键字 import和export

          • import 导入
          • export 导出
          //mian.js
          export default {
            showMsg() {
              console.log('hahahahahah')
            }
          }
          export const msg = "正是花好月圆时!"
          
          //index.js
          import module1 from "./module1"; //对应export default
          module1.showMsg()
          import { msg } from './module1'; //对应export
          console.log(msg)
          
          /*tips: 不要在html里使用<script type="module">
          import ....., 有跨域问题,可以在vscode里下载一个插件,或者本地起服务都可以解决,就不赘述了。
          </script>*/
          

          到此这篇关于JavaScript 模块化详解的文章就介绍到这了,更多相关JavaScript 模块化内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

          免责声明:
          1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

          2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
          如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
          如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

          NICE源码网 JavaScript JavaScript 模块化详解 https://www.niceym.com/21993.html