Skip to content

Commit 7080152

Browse files
committed
docs(module): edit import attributes
1 parent 1bd1156 commit 7080152

File tree

2 files changed

+8
-45
lines changed

2 files changed

+8
-45
lines changed

docs/module.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,13 @@ const configData = await import(
576576

577577
上面代码中,import 命令使用 with 子句,指定一个属性对象。这个属性对象目前只有一个 type 属性,它的值就是导入代码的类型,现在只能设置为`json`一个值。
578578

579+
如果没有 import 属性,导入 JSON 数据只能使用 fetch 命令。
580+
581+
```javascript
582+
const response = await fetch('./config.json');
583+
const json = await response.json();
584+
```
585+
579586
export 命令与 import 命令写在一起,形成一个再导出语句时,也可以使用 import 属性。
580587

581588
```javascript
@@ -584,7 +591,7 @@ export { default as config } from './config-data.json' with { type: 'json' };
584591

585592
## 模块的继承
586593

587-
模块之间也可以继承
594+
模块可以继承
588595

589596
假设有一个`circleplus`模块,继承了`circle`模块。
590597

docs/proposals.md

Lines changed: 0 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -494,47 +494,3 @@ class FakeWindow extends Realm {
494494
495495
上面代码中,`FakeWindow`模拟了一个假的顶层对象`window`
496496
497-
## JSON 模块
498-
499-
import 命令目前只能用于加载 ES 模块,现在有一个[提案](https://github.com/tc39/proposal-json-modules),允许加载 JSON 模块。
500-
501-
假定有一个 JSON 模块文件`config.json`
502-
503-
```javascript
504-
{
505-
"appName": "My App"
506-
}
507-
```
508-
509-
目前,只能使用`fetch()`加载 JSON 模块。
510-
511-
```javascript
512-
const response = await fetch('./config.json');
513-
const json = await response.json();
514-
```
515-
516-
import 命令能够直接加载 JSON 模块以后,就可以像下面这样写。
517-
518-
```javascript
519-
import configData from './config.json' assert { type: "json" };
520-
console.log(configData.appName);
521-
```
522-
523-
上面示例中,整个 JSON 对象被导入为`configData`对象,然后就可以从该对象获取 JSON 数据。
524-
525-
`import`命令导入 JSON 模块时,命令结尾的`assert {type: "json"}`不可缺少。这叫做导入断言,用来告诉 JavaScript 引擎,现在加载的是 JSON 模块。你可能会问,为什么不通过`.json`后缀名判断呢?因为浏览器的传统是不通过后缀名判断文件类型,标准委员会希望遵循这种做法,这样也可以避免一些安全问题。
526-
527-
导入断言是 JavaScript 导入其他格式模块的标准写法,JSON 模块将是第一个使用这种语法导入的模块。以后,还会支持导入 CSS 模块、HTML 模块等等。
528-
529-
动态加载模块的`import()`函数也支持加载 JSON 模块。
530-
531-
```javascript
532-
import('./config.json', { assert: { type: 'json' } })
533-
```
534-
535-
脚本加载 JSON 模块以后,还可以再用 export 命令输出。这时,可以将 export 和 import 结合成一个语句。
536-
537-
```javascript
538-
export { config } from './config.json' assert { type: 'json' };
539-
```
540-

0 commit comments

Comments
 (0)