如何在java script中使用模块

   2024-10-08 4060
核心提示:在 JavaScript 中使用模块通常有两种方式:CommonJS 和 ES6 模块。使用 CommonJS 模块:在 Node.js 等环境中,可以使用 CommonJS

在 JavaScript 中使用模块通常有两种方式:CommonJS 和 ES6 模块。

使用 CommonJS 模块:在 Node.js 等环境中,可以使用 CommonJS 模块来导入和导出模块。导出模块:
// math.jsfunction add(a, b) {  return a + b;}function subtract(a, b) {  return a - b;}module.exports = {  add,  subtract}

导入模块:

// index.jsconst math = require('./math');console.log(math.add(1, 2)); // 输出 3console.log(math.subtract(5, 3)); // 输出 2
使用 ES6 模块:在现代浏览器中,可以使用 ES6 模块来导入和导出模块。导出模块:
// math.jsexport function add(a, b) {  return a + b;}export function subtract(a, b) {  return a - b;}

导入模块:

// index.jsimport { add, subtract } from './math';console.log(add(1, 2)); // 输出 3console.log(subtract(5, 3)); // 输出 2

需要注意的是,浏览器中使用 ES6 模块时,需要在 script 标签中添加 type=“module” 属性。例如:

<script type="module" src="https://www.mykuaidi.com/static/image/lazy.gif" class="lazy" original="https://www.mykuaidi.com/static/image/nopic320.png">

总的来说,使用 ES6 模块可以让代码更加清晰和模块化,推荐在现代项目中使用 ES6 模块。

 
举报打赏
 
更多>同类维修大全