0%

Cannot use import statement outside a module

Cannot use import statement outside a module

产生这个错误的原因是因为你使用了import或者export语句,但是没有指定模块类型。在JavaScript中,有两种常用的模块类型:CommonJS和ES6 Modules。CommonJS是Node.js的模块化规范,它使用require来引入模块,使用module.exports来暴露接口。ES6 Modules是ES6的模块化规范,它使用import来引入模块,使用export来暴露接口。

解决办法

浏览器端

如果是浏览器端,需要将<script>标签的type属性设置为module,这样浏览器会将这个脚本当作ES6 Modules来处理。此时无论js文件的扩展名是.js还是.mjs都可以正常工作。

1
2
3
<script type="module">
import {add} from './math-utils.js';
</script>
1
2
3
4
// math-utils.js
export function add(a, b) {
return a + b;
}

Node.js端

方法一: 将文件的后缀名改为.mjs,这样Node.js会将这个文件当作ES6 Modules来处理。

1
2
3
4
// math-utils.mjs
export function add(a, b) {
return a + b;
}
1
2
// index.mjs
import {add} from './math-utils.mjs';

方法二: 在package.json中添加"type": "module"字段,这样Node.js会将所有的文件当作ES6 Modules来处理。

1
2
3
4
5
6
7
8
// package.json
{
"name": "json",
"version": "1.0.0",
"type": "module", // 添加这一行,就可以支持ESModule了。
"dependencies": {
}
}

总结

  • js - 常规js文件
  • mjs - ES6 Modules文件, 使用importexport来引入和暴露接口
  • cjs - CommonJS文件,使用requiremodule.exports来引入和暴露接口

Node.js环境可以使用任何上述文件格式,浏览器端其实不在意文件的后缀名,只要<script>标签的type属性设置为module,就可以使用ES6 Modules。