问题: 使用 vs code 调试js 代码,出现“SyntaxError: Cannot use import statement outside a module”
// cal.js
let count = 0;
const add = function (a, b) {
count += 1;
return a + b;
};
export { count, add };
//index.js
import { count, add } from "./cal.js" ;
console.log(count); // 0(对 calculator.js 中 count 值的映射)
add(2, 3);
console.log(count); // 1(实时反映calculator.js 中 count值的变化)
解决过程:
- npm init -y
- 在 package.json 中添加字段 type
package.json
{
"name": "promise",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
- 终端运行 node index.js 或者 vs code F5运行 都可以了。