【问题标题】:Create-React-App while attempting to run a Typescript mock api server (module loading error)尝试运行 Typescript 模拟 api 服务器时创建 React-App(模块加载错误)
【发布时间】: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


    【解决方案1】:

    所以如果有人有这个问题,答案是在我的 ui 的 package.json 中有一个脚本,它会转到我的模拟 api 文件夹并在该文件夹的 package.json 中运行一个脚本来启动 api,然后运行我的创建反应应用程序脚本。所以我将我的 root/package.json 更改为:

    "scripts": {
        "start:api": "cd mockApi && npm run start",
        "start": "run-p start:api start:dev",
        "start:dev": "cross-env REACT_APP_API_URL=http://localhost:3000 react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
    

    然后在我的根文件夹中,运行它来启动它:

    npm run start
    

    显然在我的 mockApi/package.json 我有

    "scripts": {
        "start": "ts-node server.ts"
      }
    

    这很好用。

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 1970-01-01
      • 2022-12-29
      • 2022-11-18
      • 1970-01-01
      • 2018-03-05
      • 2015-02-04
      • 1970-01-01
      • 2018-11-05
      相关资源
      最近更新 更多