zoukankan      html  css  js  c++  java
  • [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"
    }
    

    成功运行结果
    成功结果

  • 相关阅读:
    JS基础学习
    Java_iText_PDF—生成PDF工具
    vc++ 编译连接错误and解决方法
    C++ 数据类型【转】
    jsp两种include指令区别
    程序员面试宝典问题及解析
    vc++6.0快捷键
    vue动态绑定图片和背景图
    配置webpack中dev.env.js、prod.env.js,解决不同命令下项目启动和打包到指定的环境
    配置webpack中externals来减少打包后vendor.js的体积
  • 原文地址:https://www.cnblogs.com/Eyeseas/p/vscode-zhi-jie-yun-xingjs-wen-jian-bao-cuo-to-load.html
Copyright © 2011-2022 走看看