Tìm kiếm trang web

Typescript không tìm thấy tệp định nghĩa kiểu tùy chỉnh


Tôi sử dụng typescript 3.3.3 trong VS Code 1.30.2. TypeScript không thể tìm thấy tệp định nghĩa kiểu tùy chỉnh nằm trong src/@types. Mặc dù (theo như tôi biết) không cần cấu hình typeRoot trong các phiên bản TS mới nhất, nhưng tôi vẫn làm điều đó và TypeScript vẫn không thể tìm thấy tệp index.d.ts. Tên thư mục và tên module khớp nhau.

.
├── config.ts
├── node_modules
├── ormconfig.json
├── package.json
├── project_manager
├── src
├── tsconfig.json
├── tslint.json
└── yarn.lock

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "lib": [ "es2015", "dom" ],
    "target": "es2015",                       
    "module": "commonjs",                     
    "resolveJsonModule": true,
    "allowJs": true,                          
    "jsx": "react",                                               
    "outDir": "./dist",                       
    "strict": true,                           
    "noImplicitAny": true,                    
    "noImplicitThis": true,                   
    "skipLibCheck": true,
    "noUnusedLocals": true,                   
    "noUnusedParameters": true,               
    "moduleResolution": "node",                                       
    "allowSyntheticDefaultImports": true,     
    "esModuleInterop": true,                  
    "experimentalDecorators": true,           
    "emitDecoratorMetadata": true,            
    "pretty": true,
  },
  "exclude": [
    "node_modules",
    "project_manager",
    "dist",
    "@types"
  ]
}

Câu trả lời #1

Khi làm cho điều này hoạt động, bạn có thể cảm thấy như đang thực hiện một câu thần chú đúng chuẩn. Sau khi tìm kiếm cho một dự án gần đây, tôi đã phát hiện cấu hình sau trên GitHub:

  1. Đặt baseUrl của bạn thành .
  2. Thêm một ánh xạ paths cho thư mục chứa các ghi đè kiểu của bạn
  3. Tạo các tệp types-dir/module-name/index.d.ts cho các kiểu tùy chỉnh

Phần phụ nhỏ nhất của tsconfig.json sẽ trông giống như sau:

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "dist",
    "rootDir": "src",
    "paths": {
      "*": ["./types/*"]
    }
  }
}

Trong trường hợp của bạn, có lẽ bạn sẽ muốn paths trỏ đến ./src/@types/*.