模块化开发的规则 :
1. 如果你想使用 ES6 的模块化开发语法
=> 页面必须在 服务器 上打开
=> 本地打开不行
=> VS Code 下载插件, Live Server ( 会帮你配置一个虚拟服务器 )
=> 打开页面的时候, 鼠标右键 open with live server
-> 快捷键, alt + l , 再按一次 alt + o
![]()
2. 当你使用了 模块化语法 以后
=> 每一个 js 文件, 都是一个独立的 文件作用域
=> 该文件内的所有变量和方法, 都只能在这个文件内使用
=> 其他文件不能使用
=> 如果想使用, 需要 导出
3. 每一个 js 文件, 也不能使用任何其他 js 文件内部的变量
=> 如果想使用
=> 那么你需要 导入 该文件+ 导出语法 : export default { 你要导出的内容 } 导出一个默认对象, 把你想给其他文件使用的方法,书写在这个 { } 内部 + 导入语法 : import 变量 from 'js 文件' 变量得到的内容是 该 js 文件 内导出的内容
- moment 实现功能 为其他模块所使用文件
// 这里封装所有和时间操作相关的方法 // 作为一个功能函数文件出现 function format() { console.log('格式化时间') } function diffTime() { console.log('获取时间差') } const num = 100 const str = 'hello world' // 因为模块化语法的出现 // 导致这里的两个方法, 只能在该文件内使用 // 其他文件绝对不可能使用这个方法 // 如果你想让其他文件内使用这个方法 // 就要在该文件内导出你想让其他文件使用的方法 export default { // 其他文件就可以使用我这个文件内的 format 方法了 format, diffTime, num }
- 某一模块
// 我是完成某功能的模块 // 我需要一个时间格式化方法 // 我就可以使用 moment 模块内的 format 方法 // 我需要在这里导入 moment.js 文件 // 导入 moment.js import moment from './moment.js' const num = 200 console.log('我导入的 moment ', moment) console.log('完成顶部导航功能') moment.format() console.log('自己的 num ' , num) console.log('导入的 num ' , moment.num)
- 整合
// 我作为整合模块出现 // 我把所有需要用到的内容都整合在一起 import './XXX.js' import './XXX.js' ......
- 页面使用:
使用 script 标签的 src 属性引入指定的整合 js 文件
script 标签需要书写 type 属性, 值写成 module<!-- 只需要引入一个 index.js 文件 --> <!-- 因为 index.js 文件内使用着 其他需要用到的模块 --> <!-- 如果你页面引入的是一个使用了 ES6 模块化语法的 js 文件 --> <!-- 必须在服务器上打开, 并且给 script 标签添加一个 type="module" 的属性 --> <script src="./js/XXX.js" type="module"></script> // 浏览器对于带有type="module"的<script>,都是异步加载 // jQuery 支持模块加载 <script type="module"> import $ from "./jquery/src/jquery.js"; $('#message').text('Hi from jQuery!'); </script>
一、多行暴露
模块1:module1.js
//多行暴露
export function foo() {
console.log('foo() moudle1');
}
export function bar() {
console.log('bar() moudle1')
}
二、统一暴露
模块2: module2.js
function fun1() {
console.log('fun1() module2')
}
function fun2() {
console.log('fun2() module2')
}
// 统一暴露
export {foo, bar}
以上两种向外暴露方式在主文件引入时必须使用对象的解构赋值引用(不能使用变量接收的方式来映入)
主模块:main.js
import {foo, bar} from '.js/src/module1.js'
import {fun1, fun2} from './js/src/module2.js'
三、默认暴露
export default {
foo() {
console.log('默认暴露方式')
},
bar() {
console.log('默认暴露')
}
}
默认暴露的方式只允许有一个: export default { } 且在主模块引入时可以使用定义变量来接收的方式!
// 引入模块3
import module3 from '.js/src/module3.js'
// 使用模块
module3.foo()
module3.bar()