next.js - สำหรับ TypeScript ข้อผิดพลาดของ 'decorators-legacy' ตอนนี้ยังไม่ได้เปิดใช้งาน แม้ว่าฉันจะตั้งค่า experimentalDecorators และ emitDecoratorMetadata เป็น true แล้ว
ฉันใช้ typeorm กับ next.js และ typescript, tsconfig.json ของฉันคือ:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext",
"es5",
"es6"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"jsx": "preserve"
},
include: ...
}
ฉันตั้งค่า experimentalDecorator เป็น true TypeScript ของฉันคือ 3.9.7 และ TypeORM ของฉันคือ 0.2.25 ข้อผิดพลาดในการคอมไพล์คือ:
error - ./db/entity/User.ts:7:1
Syntax error: Support for the experimental syntax 'decorators-legacy' isn't currently enabled:
5 |
6 |
> 7 | @Entity()
| ^
8 | export class User {
9 |
10 | @PrimaryGeneratedColumn()
ฉันได้เปิดใช้งาน emitDecoratorMetadata แล้ว วิธีเปิดใช้งาน decorators-legacy สำหรับ tsconfig.json
คำตอบ #1
เพื่อนร่วมงานของฉันเพิ่งเจอปัญหาเดียวกัน: นี่คือข้อผิดพลาดที่เกิดขึ้นจาก Babel ซึ่งไม่สามารถจัดการกับ class decorators ได้ ในความจริง แม้ว่าคุณจะไม่ใช้ Babel ในโค้ดของคุณ Next.JS ก็ใช้มันในฝั่ง frontend
ตรวจสอบให้แน่ใจว่าคุณไม่ได้ import ./db/entity/User.ts หรือคลาส TypeORM อื่นใดในโค้ด frontend ของคุณ
คำตอบ #2
หากคุณต้องการเพียงนำเข้าประเภท User และใช้ TypeScript >= 3.8 คุณอาจสามารถทำได้โดยใช้การนำเข้าประเภทเท่านั้น เพียงเพิ่มคำว่า type หลังคำสำคัญ import วิธีนี้จะทำให้แน่ใจว่าได้นำเข้าเฉพาะประเภทของคลาสเท่านั้น จึงหลีกเลี่ยงปัญหาของ decorator ทั้งหมดเนื่องจากประเภทจะถูกละเลย/ลบโดย babel
import type { User } from "path/to/db/entity/User";
