TypeORM实体编译报错:SyntaxError: Unexpected token import
I've run into this exact issue before—let's break down what's happening and how to fix it:
Root Cause
Node.js can't parse ES module import syntax natively (in your Node 8 environment), and either your TypeScript code isn't being compiled to CommonJS properly, or TypeORM is trying to load uncompiled .ts entity files directly.
Step-by-Step Fixes
1. Verify TypeORM Entity Paths
This is the most common culprit. Make sure your TypeORM configuration (either ormconfig.json or the createConnection code) points to compiled .js files, not raw .ts sources:
If using ormconfig.json:
{ // ... other configs (database, username, etc.) "entities": ["build/**/*.js"] }
If using code-based connection setup:
// In your src/index.ts import { createConnection } from "typeorm"; createConnection({ // ... other configs entities: [__dirname + "/**/*.js"] // Uses compiled JS files });
If you accidentally point to src/**/*.ts, TypeORM will load uncompiled TypeScript files directly, which Node can't parse.
2. Validate TypeScript Compilation Output
Run tsc manually in your project root, then check the build folder for your Comment.js file. Open it—you should see require statements instead of import:
Correct compiled output example:
const typeorm = require("typeorm"); const User = require("./User"); const Debate = require("./Debate"); // ... decorated Comment class
If the compiled file still has import statements or doesn't exist at all:
- Run
tsc --noEmitto check for hidden TypeScript compilation errors - Ensure
tsconfig.jsonis in your project root directory (not nested)
3. Tweak tsconfig.json for Reliability
Your existing config is mostly correct, but add these safeguards:
{ "compilerOptions": { "lib": ["es5", "es6"], "target": "es5", "module": "commonjs", "moduleResolution": "node", "outDir": "./build", "emitDecoratorMetadata": true, "experimentalDecorators": true, "sourceMap": true, "allowJs": false, // Prevent mixing uncompiled JS with TS "strict": true // Optional, but catches more errors early }, "include": ["src/**/*"], // Explicitly include your source files "exclude": ["client"] }
4. Ensure Your Start Script Runs Compilation First
Your start command (tsc && node ./build/index.js) is correct, but double-check:
- When you run
npm start, watch the console for anytsccompilation errors. If compilation fails, Node will try to run outdated or missing files. - Delete the
buildfolder and re-runtscto ensure a clean compile.
Why Your Previous Fixes Didn't Work
Changing import to require manually breaks TypeORM's decorator metadata—those decorators rely on TypeScript's compilation process to inject metadata, so manual edits will cause more issues.
内容的提问来源于stack exchange,提问作者tootall414

