crac-webpack-rewired 中语法解决 webpack polyfills 错误

Syntax in crac-webpack-rewired to solve webpack polyfills error

我使用 create-react-app 在 React 中创建了我的项目,但过了一段时间我在控制台中遇到了这个错误

BREAKING CHANGE: webpack \< 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
\- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
\- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
@ ./node_modules/loader-utils/lib/index.js 7:25-54
@ ./node_modules/file-loader/dist/index.js 11:19-42
@ ./node_modules/file-loader/dist/cjs.js 3:15-33
@ ./src/App.js 13:0-35
@ ./src/index.js 7:0-24 11:33-36

看完this post, I reached the conclusion I had to modify the webpack.config.js that I did not have because I created the project with create-react-app. Instead of ejecting (it is not very recommended), I used the npm package advised at the end of this thread。问题是没有关于如何使用它的示例。我的问题是我必须遵循哪种语法来修改 config/webpack.extend.js?这是目前的代码:

module.exports = {
    dev: (config) => {
        //override webpack configuration
        config.externals =[..];
        return config;
    },
    prod: (config) => {
        //override webpack configuration
        config.externals =[..];
        return config;
    }
};

我试过使用 console.log(config),但它永远无法打印,因为错误会被打印回来。

您不能使用 console.log(),因为该代码不是从浏览器执行的,而是在 Webpack 的“编译”阶段。

这可能是您的案例的可能解决方案。

module.exports = {
    dev: (config) => {
      //override webpack configuration
      config.resolve.fallback = {"path": require.resolve("path-browserify")};
      return config;
    },
    prod: (config) => {
      //override webpack configuration
      config.resolve.fallback = {"path": require.resolve("path-browserify")};       
      return config;
    }
}

请注意,您必须安装软件包 path-browserfy

您还可以将 path 属性 设置为 false。