首页 > 解决方案 > Typescript 3 项目参考与第三方库(来自 npm)

问题描述

我正在使用 Typescript 并尝试与服务人员建立后台同步。有人建议我应该这样做

您可以使用单独的 tsconfig.json 文件将项目拆分为多个部分:一部分包含 dom 库,另一部分包含 webworker 库。您可以为不依赖于任一库的通用代码制作另一部分。您可以使用项目引用来帮助自动化构建。如果这不能完全解决问题,请更新问题以描述未解决的问题。

首先,我想承认我可能从根本上滥用项目参考,所以请怜悯我,互联网上的好心人。

所以现在我的项目结构是这样的:

root:
├── node_modules
│   └── [..... all the packages]
├── src
│   ├── tsconfig.json
│   └── [other source files]
├── srcWebWorker
│   └── tsconfig.json
├── structure.txt
├── tsconfig.base.json
└── tsconfig.json

在 src/tsconfig.json 中,我使用 lib dom,因为我需要它用于非服务工作者代码:

{
    "extends": "../tsconfig.base",
    "compilerOptions": {
        "lib": [ "es6", "dom", "esnext"], // ** notice I use "dom" here
    }, 
}

./srcWebworker/tsconfig.json:

{
    "extends": "../tsconfig.base",
    "compilerOptions": {
        // "outFile": "../built/local/tsc.js",
        "lib": [ "webworker" ],
    },
    "files": [

    ],
    "references": [

    ]
}

src/tsconfig.json 所指的 tsconfig.base.json :

{

    "compilerOptions": {
        "baseUrl": ".",
        "outDir": "build/dist",
        "module": "esnext",
        "target": "es6",
        "sourceMap": true,
        "allowJs": true,
        "jsx": "react",
        "moduleResolution": "node",
        "rootDir": "./src",
        "forceConsistentCasingInFileNames": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "suppressImplicitAnyIndexErrors": true,
        "noUnusedLocals": true
    }, 
    "exclude": [
        "node_modules",
        "build",
        "scripts",
        "acceptance-tests",
        "webpack",
        "jest",
        "src/setupTests.ts"
    ]
}

根目录中的 tsconfig.json:

{
    "files": [],
    "include": [],  
    "composite": true,
    "references": [
        { "path": "./src" }
    ]
}

我的理论是 scr/tsconfig 将引用和扩展 tsconfig.base.json,因此 ./src 中的代码将能够使用 --lib "dom"。但是,当我尝试编译时,出现了这个错误:

/Users/shunxuhuang/Projects/hemera/mainapp/node_modules/@types/graphql/subscription/subscribe.d.ts (17,12):找不到名称“AsyncIterator”。

我可以通过在根目录中的 tsconfig.json 中添加 lib dom来解决此错误,但是我不希望 srcWebworker 中的代码使用它,因为它与 lib webworker冲突

我试过tsc --build了,它回来了

node_modules/@types/react-dom/index.d.ts(19,72): error TS2304: Cannot find name 'Text'.
node_modules/popper.js/index.d.ts(93,13): error TS2304: Cannot find name 'CSSStyleDeclaration'.
node_modules/popper.js/index.d.ts(94,18): error TS2304: Cannot find name 'CSSStyleDeclaration'.
node_modules/popper.js/index.d.ts(122,30): error TS2304: Cannot find name 'ClientRect'.

旁注:我使用这个样板来创建我的项目,所以我不必处理 webpacking,但如果有必要,我可以弹出。

谢谢 :=)

标签: typescripttsconfigproject-reference

解决方案


尝试将lib设置更改./srcWebworker/tsconfig.json["es6", "webworker", "esnext"]. AsyncIterator中定义esnext


推荐阅读