7

我想在 typescript 中设置一个包含客户端部分(react-app)、服务器部分(express)和共享库(utils)的项目。我使用 yarn 2 工作区并希望避免使用 larna(如果可能)。不幸的是,几天以来我一直无法让它工作(还有很多谷歌搜索......)。尝试运行客户端应用程序时,我收到错误:

找不到模块“utils”或其相应的类型声明。TS2307

有人知道我做错了什么吗?

这是我的项目结构:

  • 。纱
    • 客户端(使用 create-react-app 创建)
    • utils(使用 yarn tsc --init 创建)
    • 服务器
  • .pnp.js
  • .yarnrc.yml
  • 包.json
  • 纱线锁

package.json(根):

{
  "private": true,
  "name": "monorepo with shared library and yarn 2 workspaces",
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "client": "yarn workspace client start",
    "server": "yarn workspace server start",
    "prepare": "yarn workspace utils build"
  }
}

实用程序/package.json:

{
    "name": "utils",
    "private": true,
    "version": "1.0.0",
    "main": "dist/index.js",
    "types": "dist/index.d.ts",
    "files": [
        "dist"
    ],
    "devDependencies": {
        "@types/node": "^14.14.22",
        "@typescript-eslint/eslint-plugin": "^4.14.0",
        "@typescript-eslint/parser": "^4.14.0",
        "eslint": "^7.18.0",
        "eslint-config-prettier": "^7.2.0",
        "eslint-plugin-prettier": "^3.3.1",
        "prettier": "^2.2.1",
        "typescript": "^4.1.3"
    },
    "scripts": {
        "build": "tsc -b --verbose"
    }
}

实用程序/src/index.ts:

function test() {
    console.log("this is a function from the shared library ");
}

export = {
    test
}

客户端/package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.0.0",
    "@types/react": "^16.9.53",
    "@types/react-dom": "^16.9.8",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-refresh": "^0.9.0",
    "react-scripts": "4.0.1",
    "typescript": "^4.0.3",
    "utils": "1.0.0",                 // also tried "utils": "workspace:packages/utils"
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start --verbose",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "eslint-config-react-app": "^6.0.0"
  }
}

我在 client/src/App.tsx 中添加了一个简单的导入进行测试:

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import shared from "utils";

...

谢谢!

4

1 回答 1

3

我让它工作了。“yarn workspace client add utils”成功了。

于 2021-01-27T19:33:10.140 回答