ES6 Module 的语法(十二)

ES6(ECMAScript 2015)引入了模块(Modules)的概念,使得JavaScript代码可以更容易地组织和复用。

1. export 关键字

命名导出 (Named Exports)
你可以使用 export 关键字导出多个变量、函数或类。

// module.js
export const name = 'John';
export function greet() {
  console.log('Hello, ' + name);
}
export class Person {
  constructor(name) {
    this.name = name;
  }
}

默认导出 (Default Export)
每个模块只能有一个默认导出,用 export default 来实现。

// module.js
export default function() {
  console.log('This is the default export');
}

2. import 关键字

导入命名导出 (Importing Named Exports)
使用 import 关键字可以导入其他模块的命名导出。

// main.js
import { name, greet, Person } from './module.js';

console.log(name); // John
greet(); // Hello, John
const person = new Person('Jane');
console.log(person.name); // Jane

导入默认导出 (Importing Default Export)
导入默认导出时,不需要使用大括号。

// main.js
import myFunction from './module.js';

myFunction(); // This is the default export

导入所有导出 (Importing All Exports)
可以使用 * as 语法导入一个模块的所有导出,并将其绑定到一个对象上。

// main.js
import * as myModule from './module.js';

console.log(myModule.name); // John
myModule.greet(); // Hello, John
const person = new myModule.Person('Jane');
console.log(person.name); // Jane

3. 重新导出 (Re-Exporting)

可以从一个模块中重新导出另一个模块的导出。

// module1.js
export const a = 1;
export const b = 2;

// module2.js
export { a, b } from './module1.js';
export const c = 3;

// main.js
import { a, b, c } from './module2.js';

console.log(a, b, c); // 1 2 3

4. 动态导入 (Dynamic Import)

ES2020引入了动态导入,使用 import() 函数可以在运行时按需加载模块。

// main.js
async function loadModule() {
  const module = await import('./module.js');
  module.greet(); // Hello, John
}

loadModule();

5. 具有副作用的模块 (Modules with Side Effects)

一些模块在导入时会执行一些代码,这些模块被称为具有副作用的模块。

// sideEffectModule.js
console.log('Module loaded');

// main.js
import './sideEffectModule.js'; // Module loaded

6. export 和 import 的高级用法

导出和导入时重命名
可以在导出和导入时使用 as 关键字进行重命名。

// module.js
const name = 'John';
function greet() {
  console.log('Hello, ' + name);
}
export { name as userName, greet as sayHello };

// main.js
import { userName, sayHello } from './module.js';

console.log(userName); // John
sayHello(); // Hello, John

导出时使用默认导出和命名导出

// module.js
export const name = 'John';
export default function() {
  console.log('This is the default export');
}

// main.js
import defaultFunction, { name } from './module.js';

console.log(name); // John
defaultFunction(); // This is the default export

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值