欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > JS 有哪些模块化规范

JS 有哪些模块化规范

2025/2/5 21:34:50 来源:https://blog.csdn.net/weixin_64684095/article/details/145271979  浏览:    关键词:JS 有哪些模块化规范

一、CommonJS 规范

1. 主要应用场景

主要用于服务器端开发,尤其是 Node.js 环境。

2. 核心思想

使用 `require()` 函数来引入模块,使用 `module.exports` 或 `exports` 对象来导出模块中的内容。

// math.js 模块const add = (a, b) => a + b;const subtract = (a, b) => a - b;module.exports = { add, subtract };// main.js 模块const math = require("./math.js");console.log(math.add(5, 3));console.log(math.subtract(5, 3));

二、ES6 模块规范

1. 主要应用场景

在现代浏览器和支持 ES6 及以上的环境中广泛使用,适用于前端和后端开发。

2. 核心思想

使用 `import` 关键字导入模块,使用 `export` 关键字导出模块内容。

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><title>ES6 Modules Example</title></head><body><script type="module">import { add } from "./math.js";console.log(add(5, 3));</script></body></html>
// math.jsexport const add = (a, b) => a + b;

三、AMD (Asynchronous Module Definition) 规范(了解)

1. 主要应用场景

适用于浏览器端,尤其在需要异步加载模块的情况下。

2. 核心思想

使用 `define()` 函数定义模块,模块可以异步加载,适合于在浏览器中加载外部模块,防止阻塞页面加载。

<script src="require.js"></script><script>define("math", ["require", "exports", "module"], function (require,exports,module) {const add = (a, b) => a + b;const subtract = (a, b) => a - b;exports.add = add;exports.subtract = subtract;});require(["math"], function (math) {console.log(math.add(5, 3));console.log(math.subtract(5, 3));});</script>

四、CMD (Common Module Definition) 规范(了解)

1. 主要应用场景

主要用于浏览器端,与 AMD 类似,但加载方式更倾向于就近使用。

2. 核心思想

使用 `define()` 函数,与 AMD 不同的是,模块加载完成后,会将其存储在 `factory` 函数的参数中,使用时可以按需调用。

<script src="sea.js"></script><script>define(function (require, exports, module) {const add = (a, b) => a + b;const subtract = (a, b) => a - b;exports.add = add;exports.subtract = subtract;});const math = require("./math");console.log(math.add(5, 3));console.log(math.subtract(5, 3));</script>

五、UMD (Universal Module Definition) 规范(了解)

1. 主要应用场景

旨在统一 AMD 和 CommonJS 规范,使模块可以在不同环境下使用,包括浏览器和 Node.js。

2. 核心思想

使用立即执行函数,根据当前环境判断使用 AMD、CommonJS 还是作为全局变量导出。

(function (root, factory) {if (typeof define === "function" && define.amd) {// AMDdefine(["exports"], factory);} else if (typeof exports === "object") {// CommonJSfactory(exports);} else {// 全局变量root.math = factory({});}})(this, function (exports) {const add = (a, b) => a + b;const subtract = (a, b) => a - b;exports.add = add;exports.subtract = subtract;return { add, subtract };});

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com