模块的导出与导入

本文详细介绍了JavaScript中的五种模块导出与导入方式:name、default、list、rename和ImportAll,强调了正确匹配导出和导入命名的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模块的导出与导入

这里展示了不同的导出方式和相应的导入方式。它实际上浓缩为3种类型:name、default 和 list。只要确保你的导出与你的导入方式相匹配,就不会有问题了。

// Name Export | Name Import
export const name  = 'value'
import { name } from '...'


// Default Export | Default Import
export default 'value'
import anyName from '...'


// Rename Export | Rename Import
export { name as newName }
import { newName } from '...'


// Name + Deafult | Import All
export const name = 'value'
export default 'value'
import * as anyName from '...'

// Export List + Rename | Import List + Rename
export {
	name1,
    name2  as  newName2
}
import {
    name1 as newName1,
    newName2
} from '...'

现在让我们来看看它们是如何工作的:

1. Name

这种方式主要是有一个名字,因此有了“命名”导出。

export const name = 'value';
import { name } from 'some-path/file'

console.log(name);        // 'value'

❌ 为什么没有名字,不能导出?

export 'value'

import { }   //  没有名字的话,这块花括号里不知道放什么,所以必须要有一个名字

2. Default

对于默认导出,您不需要任何名称。因为你可以给它起任何名字。

export default 'value'
import anyName from 'some-path/file'

console.log(anyName);   // 'value'

❌ 没有默认变量声明,下面这种方式是错误的导出方式:

export default const name = 'value';      // 不要尝试给一个名字

3. Mixing Default + Name(混合)

你完全可以将默认和名称导出合并到一个文件中:

export const name = 'value'
export default 'value'
import anyName, { name } from 'some-path/file';

4. Export List

这种导出方式是导出列表:

const name1 = 'value1';
const name2 = 'value2';

export {
  name1,
  name2
}
import {
  name1,
  name2
} from 'some-path/file'

console.log(
  name1, // 'value1'
  name2, // 'value2'
)

需要注意的重要一点是,这些列表不是对象,看起来是对象,但事实并非如此。这不是一个对象,这是一个导出列表!

// ❌ Export list ≠ Object
export {
  name: 'name'
}

5. Renaming Export

如果对导出名称不满意,可以使用as关键字重命名它。

const name = 'value'

export {
  name as newName
}
import { newName } from 'some-path/file'

console.log(newName); // 'value'

// 原始的名字不能再被访问
console.log(name); // ❌ undefined

❌不能将内联导出与导出列表结合使用:

export const name = 'value';

// 上面已经导出了名字 ☝️, 不需要再导出一次
export {
  name
}

6. Renaming Import

同样的规则也适用于导入。我们可以使用as关键字重命名它。

const name1 = 'value1';
const name2 = 'value2';

export {
  name1,
  name2 as newName2
}
import {
  name1 as newName1,
  newName2
} from '...'

console.log(newName1); // 'value1'
console.log(newName2); // 'value2'

// ❌  原始的名字不能再被访问
name1; // undefined
name2; // undefined

7. Import All

export const name = 'value';

export default 'defaultValue';
import * as anyName from 'some-path/file';

console.log(anyName.name); // 'value'
console.log(anyName.default); // 'defaultValue'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Joyce Lee

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

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

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

打赏作者

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

抵扣说明:

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

余额充值