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

    成功运行结果
    成功结果

  • 相关阅读:
    Redis持久化机制
    Java动态代理
    FFmpeg视频处理
    Redis集群
    解决vscode无法提示golang的问题
    解决vscode无法安装golang相关插件的问题
    近期小结
    近期小结
    稍稍解读下ThreadPoolExecutor
    响应式编程笔记三:一个简单的HTTP服务器
  • 原文地址:https://www.cnblogs.com/Eyeseas/p/vscode-zhi-jie-yun-xingjs-wen-jian-bao-cuo-to-load.html
Copyright © 2020-2023  润新知