【问题标题】:Typescript CRA with MSW: failed to parse source map带有 MSW 的 Typescript CRA:无法解析源映射
【发布时间】:2022-11-11 07:15:08
【问题描述】:

我创建了一个内置 typescript 模板的 Create React App 应用程序,然后我使用 npm 安装了 MSW,并根据 MSW 安装指南创建了文件。 它非常适合开玩笑,但是对于浏览器,当我使用启动脚本时,我收到了一堆警告:

WARNING in ./node_modules/@mswjs/interceptors/lib/utils/uuid.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '<ROOT_DIR>\node_modules\@mswjs\interceptors\src\utils\uuid.ts' file: Error: ENOENT: no such file or directory, open '<ROOT_DIR>\node_modules\@mswjs\interceptors\src\utils\uuid.ts'
 @ ./node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js 167:13-40
 @ ./node_modules/msw/lib/esm/index.js 12:0-76 1568:14-28
 @ ./src/mocks/browser.ts 3:0-34 6:22-33
 @ ./src/index.tsx 8:0-41 10:0-12

和类似的...

我找不到任何答案,所以我向您寻求帮助。

【问题讨论】:

标签: reactjs typescript msw cra


【解决方案1】:

更新:msw 0.38.0 中修复了问题。

上一个答案:

你在用react-scripts 5吗? 在那个版本的react-scripts 中使用的Webpack 5 不知何故与msw 发生冲突。

你现在有几个选择:

  1. 通过在包含GENERATE_SOURCEMAP=false 的项目根目录中添加.env 文件来禁用源映射,这样您就可以保留react-scripts 5
  2. react-scripts 降级为v4

    更多关于github issue 发布的kettanaito

【讨论】:

  • 迄今为止最新和最有用的答案
【解决方案2】:

您可以通过react-app-rewired 禁用警告,而不是禁用源映射。

  1. 添加 react-app-rewired 作为开发依赖

    yarn add -D react-app-rewired

  2. 在 package.json 中将 react-scripts 重命名为 react-app-rewired 启动、测试和构建脚本

  3. 在与 package.json as documented in source map loader 相同级别的 config-overrides.js 中添加 ignoreWarnings。

    // config-overrides.js
    module.exports = {
      webpack: function (config) {
        return { ...config, ignoreWarnings: [/Failed to parse source map/] };
      },
    };
    

【讨论】:

    【解决方案3】:

    如果您不想使用react-app-rewired,请降级为react-scripts v4 或使用GENERATE_SOURCEMAP=false,您可以查看我的想法。它很丑,但它有效。

    像这样创建一个脚本:

    const { readFileSync, writeFileSync } = require("fs");
    
    const path = "node_modules/source-map-loader/dist/utils.js";
    const regex = /.*throw new Error(`Failed to parse source map from '${sourceURL}' file: ${error}`);*/;
    
    const text = readFileSync(path, "utf-8");
    const newText = text.replace(regex, `buffer="";sourceURL="";`);
    writeFileSync(path, newText, "utf-8");
    

    然后将其添加到您的 package.json 中:

      "scripts": {
        "start": "node removeSourceMapsWarning.js && react-scripts start"
    

    显然,当source-map-loader 更改错误消息时,此代码将停止工作。但我希望到那时我们能找到真正的解决方案。

    【讨论】:

      猜你喜欢
      • 2016-07-03
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      相关资源
      最近更新 更多