无法在index.js中导入Brandade类,请求技术指导
ERR_MODULE_NOT_FOUND When Importing a TypeScript Class in Node.js Hey there, let's break down why you're hitting this error and fix it step by step!
First, Let's Diagnose the Root Causes
Your ERR_MODULE_NOT_FOUND error comes from a few overlapping issues with file naming, TypeScript compilation rules, and ESM import behavior—plus a subtle bug in your class definition:
- You’re using TypeScript syntax in a
.jsfile (Node can’t execute TypeScript directly) - Node.js ESM requires explicit file extensions for imports
- Your class has a getter/setter naming conflict that would cause an infinite recursion loop once the import works
Step-by-Step Fixes
1. Correct File Extensions & Add TypeScript Config
First, rename your TypeScript files to use the .ts extension:
- Rename
Brandade.js→Brandade.ts - Optionally rename
index.js→index.ts(to keep your codebase consistent)
Then create a tsconfig.json file in your project root to configure TypeScript compilation:
{ "compilerOptions": { "target": "ES6", "module": "ESNext", "outDir": "./dist", "strict": true, "moduleResolution": "node" }, "include": ["**/*.ts"], "exclude": ["node_modules"] }
2. Fix the Brandade Class (Resolve Recursion Bug)
Your class uses the same name nom for both the property and its getter/setter, which will trigger an infinite loop. Update it to use a private backing property:
export class Brandade{ private _nom: string; prix: number; constructor(nom: string, prix: number) { this._nom = nom; this.prix = prix; } get nom(){ return this._nom; } set nom(nom: string){ this._nom = nom; } afficher_nom(){ console.log(this._nom); } }
3. Fix the Import Path (ESM Requires Explicit Extensions)
Node.js ESM won’t auto-resolve file extensions, so you need to include the full extension in your import:
Option A: Compile to JavaScript first
- Run
tscto compile your TypeScript files into thedistfolder - Update your compiled
index.js(indist) to import the compiled class:
import {Brandade} from "./modules/Brandade.js";
- Update your
package.jsonscripts to build and run the compiled code:
"scripts": { "build": "tsc", "start": "node dist/index.js" }
Option B: Run TypeScript directly with ts-node
- Install dev dependencies:
npm install -D ts-node typescript
- Update your
index.tsimport to use the.tsextension:
import {Brandade} from "./modules/Brandade.ts";
- Update your
package.jsonstart script:
"scripts": { "start": "ts-node index.ts" }
4. Keep ESM Configuration Enabled
Leave "type": "module" in your package.json—this tells Node.js to treat files as ESM modules, which aligns with your import syntax.
Test Your Fix
Run npm start after making these changes. Your class should import successfully, and calling brandade.afficher_nom() will log the correct value without errors.
内容的提问来源于stack exchange,提问作者Rudy

