首页 > 解决方案 > 无法将类导入 index.js 文件

问题描述

225/5000

你好,

尽管我可以在 Internet 上找到所有信息,但我无法将类导入我的 index.js 文件。

index.js:

import {Brandade} from "./modules/Brandade";
const brandade = new Brandade('ma brandade',5);

Brandade.js:

export class Brandade{
    nom: string;
    prix: number;

    constructor(nom: string, prix: number) {
        this.nom = nom;
        this.prix = prix;
    }

    get nom(){
        return this.nom;
    }

    set nom(nom: string){
        return this.nom = nom;
    }

    afficher_nom(){
        console.log(this.nom);
    }
}

我收到此错误:

internalBinding ('errors'). triggerUncaughtException (
                            ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C: \ Users \ user \ OneDrive \ programming \ nodejs \ projects \ typescript_tests \ modules \ Brandade' imported from C: \ Users \ user \ OneDrive \ programming \ nodejs \ projects
\ typescript_tests \ index.js

    at finalizeResolution (internal / modules / esm / resolve.js: 276: 11)
    at moduleResolve (internal / modules / esm / resolve.js: 699: 10)
    at Loader.defaultResolve [as _resolve] (internal / modules / esm / resolve.js: 810: 11)
    at Loader.resolve (internal / modules / esm / loader.js: 85: 40)
    at Loader.getModuleJob (internal / modules / esm / loader.js: 229: 28)
    at ModuleWrap. <anonymous> (internal / modules / esm / module_job.js: 51: 40)
    at link (internal / modules / esm / module_job.js: 50: 36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

我的 package.json :

{
  "name": "typescript_tests",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "node --experimental-modules index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^14.11.8"
  }
}

你能引导我走向光明吗?

先感谢您。

标签: javascriptnode.js

解决方案


从您的 package.json 中,我可以看到您正在尝试使用 --experimental-modules 运行节点。如果是,请尝试更改:

import {Brandade} from "./modules/Brandade";

import {Brandade} from "./modules/Brandade.js";

运行 node with--experimental-modules不会自行解析文件扩展名。您可以在此处阅读有关此内容的更多信息


推荐阅读