Skip to content

Commit

Permalink
docs(module): move import.meta from proposals to module
Browse files Browse the repository at this point in the history
  • Loading branch information
ruanyf committed Oct 23, 2022
1 parent ef5e3a2 commit 7f1acfe
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 31 deletions.
31 changes: 31 additions & 0 deletions docs/module.md
Original file line number Diff line number Diff line change
Expand Up @@ -822,3 +822,34 @@ async function main() {
main();
```

## import.meta

开发者使用一个模块时,有时需要知道模板本身的一些信息(比如模块的路径)。[ES2020](https://github.com/tc39/proposal-import-meta),为 import 命令添加了一个元属性`import.meta`,返回当前模块的元信息。

`import.meta`只能在模块内部使用,如果在模块外部使用会报错。

这个属性返回一个对象,该对象的各种属性就是当前运行的脚本的元信息。具体包含哪些属性,标准没有规定,由各个运行环境自行决定。一般来说,`import.meta`至少会有下面两个属性。

**(1)import.meta.url**

`import.meta.url`返回当前模块的 URL 路径。举例来说,当前模块主文件的路径是`https://foo.com/main.js``import.meta.url`就返回这个路径。如果模块里面还有一个数据文件`data.txt`,那么就可以用下面的代码,获取这个数据文件的路径。

```javascript
new URL('data.txt', import.meta.url)
```
注意,Node.js 环境中,`import.meta.url`返回的总是本地路径,即`file:URL`协议的字符串,比如`file:///home/user/foo.js`。

**2import.meta.scriptElement**

`import.meta.scriptElement`是浏览器特有的元属性,返回加载模块的那个`<script>`元素,相当于`document.currentScript`属性。

```javascript
// HTML 代码为
// <script type="module" src="my-module.js" data-foo="abc"></script>
// my-module.js 内部执行下面的代码
import.meta.scriptElement.dataset.foo
// "abc"
```

31 changes: 0 additions & 31 deletions docs/proposals.md
Original file line number Diff line number Diff line change
Expand Up @@ -524,37 +524,6 @@ $ ./hello.js
对于 JavaScript 引擎来说,会把`#!`理解成注释,忽略掉这一行。
## import.meta
开发者使用一个模块时,有时需要知道模板本身的一些信息(比如模块的路径)。现在有一个[提案](https://github.com/tc39/proposal-import-meta),为 import 命令添加了一个元属性`import.meta`,返回当前模块的元信息。
`import.meta`只能在模块内部使用,如果在模块外部使用会报错。
这个属性返回一个对象,该对象的各种属性就是当前运行的脚本的元信息。具体包含哪些属性,标准没有规定,由各个运行环境自行决定。一般来说,`import.meta`至少会有下面两个属性。
**(1)import.meta.url**
`import.meta.url`返回当前模块的 URL 路径。举例来说,当前模块主文件的路径是`https://foo.com/main.js`,`import.meta.url`就返回这个路径。如果模块里面还有一个数据文件`data.txt`,那么就可以用下面的代码,获取这个数据文件的路径。

```javascript
new URL('data.txt', import.meta.url)
```

注意,Node.js 环境中,`import.meta.url`返回的总是本地路径,即是`file:URL`协议的字符串,比如`file:https:///home/user/foo.js`

**2import.meta.scriptElement**

`import.meta.scriptElement`是浏览器特有的元属性,返回加载模块的那个`<script>`元素,相当于`document.currentScript`属性。

```javascript
// HTML 代码为
// <script type="module" src="my-module.js" data-foo="abc"></script>
// my-module.js 内部执行下面的代码
import.meta.scriptElement.dataset.foo
// "abc"
```

## JSON 模块
import 命令目前只能用于加载 ES 模块,现在有一个[提案](https://github.com/tc39/proposal-json-modules),允许加载 JSON 模块。
Expand Down

0 comments on commit 7f1acfe

Please sign in to comment.