mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2024-04-21 12:32:22 +00:00
docs: update ES2020
This commit is contained in:
+31
-1
@@ -670,7 +670,7 @@ const myModual = require(path);
|
||||
|
||||
上面的语句就是动态加载,`require`到底加载哪一个模块,只有运行时才知道。`import`命令做不到这一点。
|
||||
|
||||
因此,有一个[提案](https://github.com/tc39/proposal-dynamic-import),建议引入`import()`函数,完成动态加载。
|
||||
[ES2020提案](https://github.com/tc39/proposal-dynamic-import) 引入`import()`函数,支持动态加载模块。
|
||||
|
||||
```javascript
|
||||
import(specifier)
|
||||
@@ -800,3 +800,33 @@ async function main() {
|
||||
}
|
||||
main();
|
||||
```
|
||||
|
||||
## import.meta
|
||||
|
||||
开发者使用一个模块时,有时需要知道模板本身的一些信息(比如模块的路径)。现在有一个[提案](https://github.com/tc39/proposal-import-meta),为 import 命令添加了一个元属性`import.beta`,返回当前模块的元信息。
|
||||
|
||||
`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`。
|
||||
|
||||
**(2)import.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"
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user