使用纱线工作区时,tsc 在 apollo-server 中找不到 express 的声明文件

tsc cannot find declaration files of express in apollo-server when using yarn workspaces

我正在尝试在其中一个包中使用 yarn workspaces(版本 3.0.2)、typescript(4.4.3)和 apollo-server(3.3.0)构建一个 monorepo。当 运行 yarn workspace graphql tsc --build 我得到以下错误:

Could not find a declaration file for module 'express'. '...../.yarn/__virtual__/express-virtual-1169aebee1/0/cache/express-npm-4.17.1-6815ee6bf9-d964e9e17a.zip/node_modules/express/index.js' implicitly has an 'any' type.
  If the 'express' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express'

2 import express from 'express';
                      ~~~~~~~~~

然后我尝试安装 @types/express,但错误仍然存​​在。我该如何解决这个问题?

我的项目结构如下:

├── package.json
├── packages
│   └── graphql
│       ├── index.ts
│       ├── package.json
│       └── tsconfig.json
└── yarn.lock

我尝试编译的index.ts文件:

import { gql } from 'apollo-server';

// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
  # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.

  # This "Book" type defines the queryable fields for every book in our data source.
  type Book {
    title: String
    author: String
  }

  # The "Query" type is special: it lists all of the available queries that
  # clients can execute, along with the return type for each. In this
  # case, the "books" query returns an array of zero or more Books (defined above).
  type Query {
    books: [Book]
  }
`;

我的tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "incremental": true,
    "noUnusedLocals": true,
    "esModuleInterop": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": "./src",
    "skipLibCheck": false
  },
  "include": ["**/*.ts"],
  "compileOnSave": true
}

我的根package.json:

{
  "name": "test-monorepo",
  "packageManager": "yarn@3.0.2",
  "private": true,
  "workspaces": [
    "packages/*"
  ]
}

我的 package.json 的 graphql 包:

{
  "name": "graphql",
  "packageManager": "yarn@3.0.2",
  "dependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^16.9.1",
    "apollo-server": "^3.3.0",
    "graphql": "^15.5.3",
    "typescript": "^4.4.3"
  }
}

在您的 tsconfig.json 文件中,将 skipLibCheck 更改为 true。这将跳过声明文件的类型检查。

apollo-server 没有包含 @types/express 作为 peerDependency。解决方法是告诉yarn包apollo-server需要@types/express in .yarnrc.yaml:

packageExtensions:
  apollo-server@*:
    dependencies:
      "@types/express": "*"