Tìm kiếm trang web

javascript - TypeScript & NodeJS: Exports không được định nghĩa trong phạm vi module ES


Tôi đã viết các tệp JavaScript NodeJS của mình với cú pháp Import/Export và file package.json của tôi có "type" : "module"

Vấn đề là sau khi tsc xây dựng mã, mã đã được chuyển đổi trong /build/server.js không thể chạy. Nó báo Exports is not defined in ES module scope

Đây là tsconfig.json của tôi

{
  "compilerOptions": {
    "resolveJsonModule": true,
    "incremental": true,
    "target": "es2019" ,
    "module": : "commonjs",
    "allowJs": true ,
    "outDir": "./build",
    "strict": true ,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true ,
    "alwaysStrict": true ,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true ,
    "inlineSourceMap": true ,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true ,
    "forceConsistentCasingInFileNames": true,
    "useUnknownInCatchVariables": false
  }
}

nếu tôi gỡ bỏ "module" : "commonjs" và thêm "moduleResolution": "Node", tôi nhận được một lỗi khác với các import của mình:

Không thể tìm thấy module /build/constants được import từ /build/server.js Module /build/constants.js thực sự tồn tại, nhưng trong mã của tôi tôi không thêm .js vào các import, vì vậy tôi đang import nó như sau import {CONSTANTS} from 'constants'.

Trong một tệp TypeScript, khi nhập các tệp TypeScript khác, liệu việc nhập khẩu nên như import {CONSTANTS} from constants.js hay import {CONSTANTS} from constants.ts hay import {CONSTANTS} from constants, đó là cách mà tôi đang làm hiện tại.

Tôi mới làm quen với TypeScript. Cách tốt nhất để giải quyết vấn đề mà tôi đang gặp phải là gì?

Cảm ơn

Câu trả lời #1

Tôi đã tìm ra giải pháp. "type" : "module" phải được gỡ khỏi package.json

Bài viết liên quan