es6 class模块化导出与引用核心是按需加载、作用域隔离:默认导出适用于单主类(import button from './button.js'),命名导出适用于多类共存(import { input, select } from './components.js'),需注意type="module"、路径带扩展名及避免commonjs混用。

ES6 Class 的模块化导出与引用,核心在于把类当作一个可复用、可隔离的单元,通过 export 暴露出去,再用 import 在其他文件中使用——不是直接挂全局,而是按需加载、作用域干净。
默认导出类(推荐用于主类)
当一个模块只封装一个核心类时,用 export default 最简洁。导入时不需花括号,名字可自定义(但建议保持一致,提升可读性):
-
导出(
Button.js):export default class Button {<br> constructor(text) { this.text = text; }<br> render() { return `<button>${this.text}</button>`; }<br>} -
引用(
app.js):import Button from './Button.js';<br>const btn = new Button('提交');<br>console.log(btn.render());
命名导出类(适合多个类共存)
如果一个文件定义了多个类(如 Input、Select、Form),就用命名导出。导入时必须用花括号,并严格匹配导出名(或重命名):
-
导出(
components.js):export class Input { /* ... */ }<br>export class Select { /* ... */ }<br>export const DEFAULT_SIZE = 'medium'; -
引用(
page.js):import { Input, Select, DEFAULT_SIZE } from './components.js';<br>import { Input as TextInput } from './components.js'; // 重命名
类配合静态成员与继承的导出
类中的 static 方法/属性属于类本身,不随实例创建;继承时子类需在 constructor 中调用 super()。这些特性在模块化中照常工作:
- 父类导出:
export default class Animal { static type = 'mammal'; } - 子类继承并导出:
import Animal from './Animal.js';<br>export class Dog extends Animal { constructor(name) { super(); this.name = name; } } - 使用时可分别导入:
import Animal, { Dog } from './animals.js';
注意事项与常见陷阱
模块化不是语法糖,它有运行约束,稍不注意就会报错:
-
脚本类型必须声明:HTML 中引入模块需加
type="module",否则import/export无效:<script type="module" src="app.js"></script> -
路径必须带扩展名或斜杠:Node.js 和现代浏览器要求模块路径显式(如
'./Button.js',不能写'./Button') -
不能混用 CommonJS:在纯 ES 模块中,
require()和module.exports不可用 -
循环依赖要警惕:A 导入 B,B 又导入 A,可能导致未定义行为;可通过延迟导入(如函数内
import())缓解











