[vscode直接運行js文件報錯]: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.


報錯示例:

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"
}

成功運行結果
成功結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM