Я пробовал использовать модули Polyfill в webpack 5, но не работал (Reactjs)

Привет, ребята, я новичок в React, когда я начинаю свой проект, я получаю сообщение об ошибке Wepback V5

Это то, что использую!

      Os: Win11
Node : v16
React:v17
React-script : v5
Webpack:v5

Это сообщение об ошибке содержит

      Crypto
Http
Https
Stream

Вывод ошибок

Скомпилировано с проблемами: X

      ERROR in ./node_modules/eth-lib/lib/bytes.js 9:193-227

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\PC\Desktop\Portfolio\portfolio_app\node_modules\eth-lib\lib'

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: { "crypto": require.resolve("crypto-browserify") }'
    - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "crypto": false }


ERROR in ./node_modules/web3-eth-accounts/lib/index.js 31:74-91

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\PC\Desktop\Portfolio\portfolio_app\node_modules\web3-eth-accounts\lib'

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: { "crypto": require.resolve("crypto-browserify") }'
    - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "crypto": false }


ERROR in ./node_modules/web3-eth-accounts/node_modules/eth-lib/lib/bytes.js 7:193-227

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\PC\Desktop\Portfolio\portfolio_app\node_modules\web3-eth-accounts\node_modules\eth-lib\lib'

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: { "crypto": require.resolve("crypto-browserify") }'
    - install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
    resolve.fallback: { "crypto": false }

Изображение содержит вывод

Сообщение об ошибке Webpack5

10 ответов

Я устраняю эти ошибки, но мое приложение не отображается. Если вы заинтересованы в устранении этих ошибок, вы можете вставить код прямо в your-project/node_modules/react-scripts/config/webpack.config.jsно эти изменения могут быть перезаписаны после перестроения вашего приложения. Найдите в объекте module.exports разрешение и напишите резервную копию, в вашем случае это «крипто»: require.resolve("crypto-browserify").

И установить зависимость npm install crypto-browserify.

      resolve: {
//   fallback: {
//     "fs": false,
//     "tls": false,
//     "net": false,
//     "http": require.resolve("stream-http"),
//     "https": false,
//     "zlib": require.resolve("browserify-zlib") ,
//     "path": require.resolve("path-browserify"),
//     "stream": require.resolve("stream-browserify"),
//     "util": require.resolve("util/"),
       "crypto": require.resolve("crypto-browserify")
} 

Или вы можете добавить запасной вариант, используя react-app-rewired, как описано в Github https://github.com/facebook/create-react-app/issues/11756 . Установите react-app-rewired, создайте config-overrides.jsфайл в корне вашего проекта. Мой код в файле

      module.exports = function override (config, env) {
    console.log('override')
    let loaders = config.resolve
    loaders.fallback = {
        "fs": false,
        "tls": false,
        "net": false,
        "http": require.resolve("stream-http"),
        "https": false,
        "zlib": require.resolve("browserify-zlib") ,
        "path": require.resolve("path-browserify"),
        "stream": require.resolve("stream-browserify"),
        "util": require.resolve("util/"),
        "crypto": require.resolve("crypto-browserify")
    }
    
    return config
}

В package.json измените скрипты с 'start': 'react-scripts start'к 'start': 'react-app-rewired start'. Затем запустите запуск проекта npm или запуск пряжи.

Я решил свою проблему следующим образом:

      npm uninstall react-scripts
npm install react-scripts@4.0.3

Чтобы использовать polyfill в webpack 5 в reactjs, выполните следующие действия:

  1. Первая установка npm install node-polyfill-webpack-pluginмодуль (ссылка: https://www.npmjs.com/package/node-polyfill-webpack-plugin)

  2. Затем перейдите к webpack.config.js -> node-module -> react-scripts -> config -> webpack.config.js.

  3. Затем добавьте ниже код:

      const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")

module.exports = {
    // Other rules...
    plugins: [
        new NodePolyfillPlugin()
    ]
}

Мое решение заключается в использованииCracoмодуль для переопределения модуля Webpack ModuleScopePlugin и его разрешения на использование модулей, совместимых с браузером.

Вы также можете использоватьreact-app-rewireмодуль.

Добавьте другие модули Node.js вrequire.resolveполе, если вам нужно.

  1. Установить модули
      yarn add @craco/craco crypto-browserify path-browserify stream-browserify -D
  1. Добавлятьcraco.config.js
      module.exports = {
  webpack: {
    configure: webpackConfig => {
      const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
        ({ constructor }) => constructor && constructor.name === 'ModuleScopePlugin'
      );

      webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);
      webpackConfig['resolve'] = {
        fallback: {
          path: require.resolve("path-browserify"),
          crypto: require.resolve("crypto-browserify"),
          stream: require.resolve("stream-browserify"),
        },
      }
      return webpackConfig;
    },
  },
};
  1. Заменить поля скриптов вpackage.json
      "scripts": {
  "start": "craco start",
  "build": "craco build",
  "test": "craco test",
  "eject": "craco eject"
},

Это похоже на новую проблему со многими пакетами, включая web3, поскольку они несовместимы с Webpack v5 без добавления запасных вариантов для полифилов.

Проблема отмечена здесь: https://github.com/facebook/create-react-app/issues/11756

Я решил эту проблему, добавив запасной вариант в мой файл webpack.config.js;

      module.exports = {
    resolve: {
        fallback: {
            assert: require.resolve('assert'),
            crypto: require.resolve('crypto-browserify'),
            http: require.resolve('stream-http'),
            https: require.resolve('https-browserify'),
            os: require.resolve('os-browserify/browser'),
            stream: require.resolve('stream-browserify'),
        },
    },
};

но также нужно, но есть ошибки компиляции в процессе сборки:

      FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory" error

это было решено путем добавления в мой файл .env;

      GENERATE_SOURCEMAP=false

надеюсь это поможет.

Поскольку у меня недостаточно репутации, чтобы редактировать или комментировать этот ответ , мне пришлось создать новый ответ, который мне подходит. В принципе, также необходимо установитьreadline.

А именно:

      npm uninstall react-scripts
npm install react-scripts@4.0.3
npm install readline

В моем случае импорт неиспользуемого компонента привел к ошибке. Просто удалите ненужный импортированный компонент.

импортировать {ReactDOM} из "React"

я преодолел эту проблему, набрав

      npm audit fix --force

шаг 1) добавить в package.json "webpack": "^4.44.2" шаг 2) снова удалить модули узла и npm i или установить пряжу

закройте приложение и запустите снова, запуск пряжи или запуск npm

Другие вопросы по тегам