Cannot use import statement outs

2020-08-11  本文已影响0人  王国的荣耀

问题: 使用 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运行 都可以了。
上一篇 下一篇

猜你喜欢

热点阅读