【发布时间】:2021-02-08 08:11:56
【问题描述】:
我有一个使用 create-react-app 创建的客户端应用程序,它使用打字稿。我的目录结构是这样的(如有混淆请见谅):
-MyApp (folder)
-node_modules (folder)
-package.json (has a script that runs the react client app and the mockApi using, 'ts-node mockApi/server.ts')
-tsconfig.json (this uses module:esnext because apparently CRA requires it?)
-src (folder)
-components
etc.
-MockApi (folder level with MyApp)
-tsconfig.json (uses module:commonJS for server.ts)
-server.ts (creates a json-server in express/node using import syntax)
-mockData (folder)
-index.ts (gathers domain types into single objects)
-someEntity.ts (domain type)
我的主 package.json 中有几个脚本。一个运行命令“ts-node mockData/server.ts”以将我的打字稿模拟 api 加载到它自己的端口上。另一个脚本运行正常的 react-scripts 以在 localhost:3000 上加载 react 客户端。我正在使用一个允许并行脚本的库。
在我将它添加到我现有的应用程序之前,我使用 typescript 和 json-server 在它自己的项目中创建了模拟 api,以确保它能够正常工作,并且确实如此。但是 api 的 tsconfig 中的“模块”键需要是“CommonJS”才能进行动态导入。我认为如果模拟 api 将自己的 tsconfig 文件设置为 CommonJS,它将在 create-react-app 项目中工作。但是加载api的脚本会出错。
当我运行它时,它说“import xxxx 不是一个模块”(在 server.ts 中)。 package.json 脚本使用我的主项目中的 tsconfig 设置来加载 server.ts 文件,使用“module:esnext”,而不是我的 api tsconfig 中定义的 commonJS。如何告诉它使用其他 tsconfig 中的设置?
这是我的 CRA package.json 中的脚本部分:
"scripts": {
"start": "run-p start:dev start:api",
"start:dev": "cross-env REACT_APP_API_URL=http://localhost:3000 react-scripts start",
"start:api": "ts-node ./mockApi/server.ts",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
start:api 脚本在我的 server.ts 中爆炸(第一次导入):
import jsonServer from "json-server";
import mockData from "./mockData/index";
难道不能用 create-react-app 做我想做的事吗?我试图对此进行研究,但找不到任何提及此特定问题的内容。每个 json-server 示例都在 JS 中。但是 json-server 有 TS 的 @types 所以我不明白为什么没有记录这个问题。当然其他人使用带有 Json-server 和 c-r-a 的 Typescript。
谢谢
【问题讨论】:
标签: node.js typescript create-react-app tsconfig json-server