其他分享
首页 > 其他分享> > [vscode直接运行js文件报错]: To load an ES module, set "type": "module" in the package.js

[vscode直接运行js文件报错]: To load an ES module, set "type": "module" in the package.js

作者:互联网

报错示例:

vscode报错截图

报错原因:

在vscode里面编写了一段js代码,使用了import来引入一个函数并调用

代码复现

// inherit() returns a newly created object that inherits properties from the
// prototype object p.  It uses the ECMAScript 5 function Object.create() if
// it is defined, and otherwise falls back to an older technique.
export function inherit(p) {
    if (p == null) throw TypeError(); // p must be a non-null object
    if (Object.create)                // If Object.create() is defined...
        return Object.create(p);      //    then just use it.
    var t = typeof p;                 // Otherwise do some more type checking
    if (t !== "object" && t !== "function") throw TypeError();
    function f() {};                  // Define a dummy constructor function.
    f.prototype = p;                  // Set its prototype property to p.
    return new f();                   // Use f() to create an "heir" of p.
}

//报错的罪魁祸首
import {inherit} from "./inherit.js"
 
var p = {
    x:1.0,
    y:1.0,
    get r(){
        return Math.sqrt(this.x**2+this.y**2)
    },
    set r(newValue){
        let oldValue = Math.sqrt(this.x**2+this.y**2)
        let ratio = newValue/oldValue
        this.x *= ratio
        this.y *= ratio
    }
}
var q = inherit(p)
q.x = 3
q.y = 4

console.log(q.r)

解决方案

在package.json里面加入type:"module"字段

npm init -y

//package.json
{
  "name": "javascript-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  //新增以下这行
  "type": "module",
  "dependencies": {},
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

成功运行结果
成功结果

标签:load,function,create,Object,inherit,报错,module
来源: https://www.cnblogs.com/Eyeseas/p/vscode-zhi-jie-yun-xingjs-wen-jian-bao-cuo-to-load.html