1. 程式人生 > 實用技巧 >[vscode直接執行js檔案報錯]: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

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

報錯示例:

報錯原因:

在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)