模块化语法
-
- 面向过程
-
- 面向对象
-
- 函数式编程
-
- 模块化语法
-
- 组件化编程 (html + css + js)
- 引入 JS 的时候, 需要配置一个 type 值为 module
- 页面必须以服务器的形式打开, 目前可以借助 live server
-
导出语法1
export default 要导出的内容(每个文件只能有一个默认导出)
-
导出语法2
export 定义变量 = 值(每个文件可以有多个这种导出)
-
导入语法1
export 变量名 from '文件.js' 这种导入方式对应的+ + 导入语法2
export {导出的内容1, 导出的内容2, ...} from '文件.js' 这种导入方式对应的是导出语法2
1.引入JS文件
<!-- index.js 是一个总的 JS 文件, 会将你项目中的所有 JS 文件, 整合到他的内部 -->
<script src="./index.js" type="module"></script>
2.index.js文件整合JS
console.log("我是 index.js, 我负责资源整合");
// import comAObj from './comA' // 这样不写文件后缀浏览器识别不了
import comAObj from "./comA.js"; // 所以必须带上文件后缀
// console.log(comAObj);
import { comBObj, arr, fn } from "./comB.js";
console.log(comBObj);
console.log(arr);
console.log(fn);
3.书写A模块
console.log("我是当前整个项目的一个小模块");
const fn = () => {
console.log("我是 comA.js 内部的一个 fn 函数");
};
const arr = ["汽车", "自行车", "电动车", "摩托车"];
// 当前 JS 文件内部的 内容, 是一个独立作用域, 如果想给外边的 JS 文件使用, 需要导出一些内容
// export default '你需要导出的内容, 当前为默认导出, 一个文件只能有一个'
const obj = {
fn,
arr,
};
export default obj; // 将来谁想用这个文件的内容, 需要导入语法, 将这个对象导入到他的 文件中
4.书写B模块
console.log("我也是当前整个项目的一个小模块, 我是 comB.js");
export const comBObj = {
name: "张三",
age: 18,
};
export const arr = ["炸酱面", "烩面", "打卤面", "窝子面", "热干面"];
export const fn = () => {
console.log('我是 comB.js 的一个 函数')
}