Typescript CRA与MSW:无法解析源映射

12
我使用typescript模板构建了一个Create React App应用程序,然后使用npm安装了MSW,并根据MSW的安装指南创建了文件。
对于jest来说完美运行,但是当我使用start脚本时,在浏览器中会收到一堆警告消息:
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

和相似的内容...

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


这个问题在 GitHub 上有一个未解决的问题。请在那里关注它。谢谢。 - kettanaito
3个回答

19

更新:问题已在msw 0.38.0中修复。

之前的回答:

你正在使用react-scripts 5吗? 在react-scripts的那个版本中使用的Webpack 5msw有些冲突。

现在你有几个选择:

  1. 通过在项目根目录下添加一个.env文件,并将GENERATE_SOURCEMAP=false列入其中,来禁用源映射,以便保留react-scripts 5
  2. react-scripts降级到v4

更多信息请参见Github问题,由kettanaito发布。


1
迄今为止最更新且有用的答案 - Alan Yong

1

不要禁用源映射,你可以通过 react-app-rewired 来禁用警告。

  1. 将 react-app-rewired 添加为 dev 依赖项

    yarn add -D react-app-rewired

  2. 在 package.json 的 start、test 和 build 脚本中将 react-scripts 重命名为 react-app-rewired

  3. 在 config-overrides.js 中添加 ignoreWarnings,与 package.json 处于同一级别,详细文档请参见source map loader

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

0

如果您不想使用 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更改错误信息时,此代码将停止工作。但我希望到那时我们会有一个真正的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接