ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2020-09-06 15:32:53  阅读:721  来源: 互联网

标签:load function create Object inherit 报错 module


报错示例:

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有