如何调试从 create-react-app 创建的应用程序使用的本地打字稿模块

Posted

技术标签:

【中文标题】如何调试从 create-react-app 创建的应用程序使用的本地打字稿模块【英文标题】:How do I debug a local typescript module used by an app created from create-react-app 【发布时间】:2019-12-27 13:41:04 【问题描述】:

我正在创建一个 Web 应用程序,它使用 express 作为后端(webapp/server)和 React 作为前端(webapp/client)(项目结构见下文)。 我使用 create-react-app 创建了我的反应应用程序。 我需要一个服务器和客户端都使用的通用模块。所以我创建了一个名为“common”的本地模块,并使用“npm link”将其提供给我的客户端和服务器

common 文件夹在 /src 中有一个类,在构建它时,我会在 /dist 文件夹中获取已编译的 js、类型和源映射。

我的项目结构

webapp
|
|--common
   |--src
      |--Service.ts
   |--dist
      |--Service.js
      |--Service.d.ts
      |--Service.js.map
|
|--client
   |--src
      |--App.ts
|--server

App.ts

import Service from "common"
...
var _service:Service = new Service();
_service.doStuff();
...

我在导入服务、构建和运行 react 应用程序时没有遇到任何问题。

问题

问题是当我尝试从 react 应用程序调试服务时,我得到的是编译后的 Service.js 而不是原来的 Service.ts。

调试在服务器端代码上按预期工作。

我认为问题的根源是 create-react-app 使用 webpack 构建应用程序,当它解决模块依赖关系时,它忽略了原始源映射并将 .js 文件添加到其最终包中(主要.chunk.js 和 main.chunk.js.map)

实际

main.chunk.js.map --> has path to common/dist/Service.js

预期

main.chunk.js.map --> has path to common/src/Service.ts

【问题讨论】:

【参考方案1】:

我想出了如何通过我的 react 应用进行调试。

关键是不要在react app中使用构建好的js文件,而是在react项目中自己引用ts文件。我终于使用 react-app-rewired 为 react 项目重新配置了我的 webpack 配置。有两件事要做。

为 tsconfig 中的 common 模块添加了别名

  "compilerOptions": 
   ...
    "paths": 
      "@common": ["my-common-module/src/index.ts"]
    
  

更新了 webpack 配置并进行了以下更改(使用 config-overrides.js 进行 react-app-rewired)

使用 awesome-typescript-loader 加载上述 ts 文件 移除 ModuleScopePlugin 以从 /src 目录外导入通用模块 添加了别名,以便 webpack 可以知道 @common 别名的用途

最终的 config-overrides 文件应如下所示:

/* config-overrides.js */
const rewireAliases = require("react-app-rewire-aliases");
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');

var path = require("path");

module.exports = function override(config, env) 
  config.module.rules.push(
    test: /\.ts$/,
    use: ["awesome-typescript-loader"],
    enforce: "pre"
  );

  config.resolve.plugins = config.resolve.plugins.filter(plugin => !(plugin instanceof ModuleScopePlugin));

  config = rewireAliases.aliasesOptions(
    "@common": path.resolve(
      __dirname,
      `node_modules/my-common-module/src/index.ts`
    )
  )(config, env);

  return config;
;

【讨论】:

以上是关于如何调试从 create-react-app 创建的应用程序使用的本地打字稿模块的主要内容,如果未能解决你的问题,请参考以下文章

如何在 create-react-app 上调试 jest 单元测试?

从create-react-app迁移到vite

如何使 http-proxy-middleware 从 create-react-app 连接到 localhost 服务器

使用 create-react-app 构建开发/调试构建

在create-react-app中调试es6

如何从默认的“rails new app”和“npx create-react-app”修复这些依赖问题?