【ES6】模块化

概述

模块功能主要有两个命令,exportimport

一个js文件就是一个模块。

参考视频

【一小时速通JavaScript模块化,涵盖CommonJS与ES6模块化-哔哩哔哩】 https://b23.tv/gZ1uK7V

导出成员

在正常变量、函数前加export关键字。

导入模块

在另一个模块中导入

万能导入
javascript 复制代码
import * as xxx from "xxx.js"

在HTML页面导入

html 复制代码
<script type="module" src="">

模块化的优点

防止命名冲突,每个模块都有自己的命名空间

  • 代码复用,每个模块可以被其他多个模块引用
  • 高维护性,修改一个模块其他引用该模块的地方都改变
  • 确保引入顺序的正确性,使用模块化之后一般都是在自己的中引入所依赖的模块,所以避免了依赖顺序的引入问题
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="Point.js"></script>
</head>
<body>
    
</body>
    <script src="run.js"></script>
</html>

引入Point.js,再在run.js中创建实例和执行其他代码。

而通过模块化,可以直接在run.js中导入和使用Point.js中定义的类。

javascript 复制代码
import {Point,ColorPoint} from "./Point.js";

let cp = new ColorPoint(100,100,"red");

console.log(cp);

HTML代码也就可以简化:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
    <script type="module" src="run.js"></script>
</html>

需要注意的是,模块功能貌似需要服务器,可以使用Live Server插件,以本地静态服务器形式运行网页。

相关推荐
子兮曰4 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖4 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神4 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛7 小时前
Nginx日志切分
服务器·前端·nginx
北原_春希7 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
尽意啊7 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜7 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive7 小时前
Vue3使用ECharts
前端·javascript·echarts
竹秋…7 小时前
echarts自定义tooltip中的内容
前端·javascript·echarts
宝贝露.7 小时前
Axure引入Echarts图无法正常显示问题
前端·javascript·echarts