Cannot use import statement outside a module

问题: 使用 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值的变化)

解决过程:

  1. npm init -y
  2. 在 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"
}

  1. 终端运行 node index.js 或者 vs code F5运行 都可以了。
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容