docs(module-loader): edit 同时支持两种格式的模块

This commit is contained in:
ruanyf
2020-08-20 14:19:23 +08:00
parent 09accf90d9
commit 7b8c0632f6
2 changed files with 9 additions and 6 deletions
+8 -6
View File
@@ -478,7 +478,7 @@ import packageMain from 'commonjs-package';
import { method } from 'commonjs-package';
```
这是因为 ES6 模块需要支持静态代码分析,而 CommonJS 模块的输出接口是`module.exports`,无法被静态分析,所以只能整体加载。
这是因为 ES6 模块需要支持静态代码分析,而 CommonJS 模块的输出接口是`module.exports`是一个对象,无法被静态分析,所以只能整体加载。
加载单一的输出项,可以写成下面这样。
@@ -514,17 +514,19 @@ cjs === 'cjs'; // true
```javascript
import cjsModule from '../index.js';
export const foo = cjsModule.foo;
export const foo = cjsModule.foo;
```
上面代码先整体输入 CommonJS 模块,然后再根据需要输出具名接口。最后,可以将它放在一个子目录,再放一个单独的`package.json`文件,指明`{ module: "type" }`
上面代码先整体输入 CommonJS 模块,然后再根据需要输出具名接口。
你可以把这个文件的后缀名改为`.mjs`,或者将它放在一个子目录,再在这个子目录里面放一个单独的`package.json`文件,指明`{ module: "type" }`
另一种做法是在`package.json`文件的`exports`字段,指明两种格式模块各自的加载入口。
```bash
"exports"{
"require": "./index.js"
"import": "./esm/wrapper.js"
"exports"{
"require": "./index.js"
"import": "./esm/wrapper.js"
}
```
+1
View File
@@ -227,6 +227,7 @@
- Axel Rauschmayer, [Making transpiled ES modules more spec-compliant](http://www.2ality.com/2017/01/babel-esm-spec-mode.html): ES6 模块编译成 CommonJS 模块的详细介绍
- Axel Rauschmayer, [ES proposal: import() dynamically importing ES modules](http://www.2ality.com/2017/01/import-operator.html): import() 的用法
- Node EPS, [ES Module Interoperability](https://github.com/nodejs/node-eps/blob/master/002-es-modules.md): Node 对 ES6 模块的处理规格
- Dan Fabulich, [Why CommonJS and ES Modules Cant Get Along](https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1): Node.js 对 ES6 模块的处理
## 二进制数组