How to Polyfill node core modules in webpack 5
Asked Answered
S

37

424

webpack 5 no longer do auto-polyfilling for node core modules. How to fix it please?

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.

errors

Sire answered 27/10, 2020 at 15:25 Comment(4)
I tried the solutions mentioned here and without success: github.com/webpack/webpack/issues/11868Sire
try this solution alchemy.com/blog/how-to-polyfill-node-core-modules-in-webpack-5Cacilia
For Gatsby users, see #68884921 to modify gatsby-node.js instead of config-overrides.jsPerron
maybe you are adding this import mistake : import { text } from "body-parser";Ecumenism
W
169

I was also getting these error's when upgrading from webpack v4 to v5. Resolved by making the following changes to webpack.config.js

added resolve.fallback property

removed node property

{
resolve: {
  modules: [...],
  fallback: {
    "fs": false,
    "tls": false,
    "net": false,
    "path": false,
    "zlib": false,
    "http": false,
    "https": false,
    "stream": false,
    "crypto": false,
    "crypto-browserify": require.resolve('crypto-browserify'), //if you want to use this module also don't forget npm i crypto-browserify 
  } 
},
entry: [...],
output: {...},
module: {
  rules: [...]
},
plugins: [...],
optimization: {
  minimizer: [...],
},
// node: {
//   fs: 'empty',
//   net: 'empty',
//   tls: 'empty'
// },
}

upgrade from v4 to v5 => https://webpack.js.org/migrate/5/#clean-up-configuration

Wayward answered 12/11, 2020 at 11:7 Comment(13)
What do you put in the node_modules : [...] ?Lyceum
@JustinMeskan I used it to search node modules or custom modules from root directories. modules: [ path.resolve('./src'), path.resolve('./node_modules'), ], Ref: webpack.js.org/configuration/resolve/#resolvemodulesWayward
In what file have you made these edits? Not even the webpack migration guide you linked seems to mention this.Midstream
@Midstream usually we set webpack configs in webpack.config.js file in the root folder of your app. webpack.js.org/configurationWayward
where do we add resolve.fallback property???Phototopography
@BrianIvanderT.P. you should add it inside webpack.config.js file.Wayward
@MaqsoodAhmed I do not appear to have this file (webpack.config.js) in the root folder of my app???Opera
@Opera I think you created project using create-react-app. So, you can may get config file by ejecting project OR by going into react-scripts node_modules folder. #48396304Wayward
Thanks so much! I went from 190 errors to five firebase-related errors and one google auth error. This is a lot more manageable.Watson
If you have a react app created with create-react-app you can't just override the config. If you don't want to eject you need either craco or react-app-rewired to make the webpack config changes.Jeanett
React does not read your webpack.config.js file. You have to use craco instead to override the react internal webpack. create craco.config.js in your root folder and then add this to it const path = require('path');module.exports = {webpack: {configure: { resolve: {fallback: {crypto: require.resolve('path-browserify'), },},},},}; then update your package.json to start with craco ie ` "scripts": {"start": "craco start",}, `Headstall
I use angular 16.1.6 and it isn't working for meMecke
Can someone explain me why this error is actually occuring? like what is making this error happen?Helbonnah
W
123

Re-add support for Node.js core modules with node-polyfill-webpack-plugin:

With the package installed, add the following to your webpack.config.js:

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

module.exports = {
    // Other rules...
    plugins: [
        new NodePolyfillPlugin()
    ]
}
Witherite answered 4/1, 2021 at 2:20 Comment(8)
This fixed most of the errors, but not all. I still needed to fix 'fs' and 'path-browserify' using @lukas-bach 's solution.Adriannaadrianne
@Adriannaadrianne I'm open to suggestions for improvement. How should fs be polyfilled in the browser? Should we just lie with a shim?Witherite
I take back what I said, node-polyfill-webpack-plugin worked great for my client bundling. I was also bundling server side code which needed 'fs' and 'path-browserify'. Once I applied your plugin to only my client build it worked great.Adriannaadrianne
everyone keeps mentioning webpack.config.js file, I cannot find it in the root folder of my app. Please can soneone advise?Opera
@Opera You'll need to find where Webpack is getting its config fromWitherite
@Opera if you are using create-react-app, the webpack.config.js can be found in node_modules/react-scripts (https://mcmap.net/q/82119/-where-is-create-react-app-webpack-config-and-files). To edit the webpack configuration of a CRA project, you might want to consider the react-app-rewired package (npmjs.com/package/react-app-rewired).Oquendo
'fs' module does'nt seem to be polyfilled.Hersch
After adding this to my config I'm getting "Module not found: You attempted to import /node_modules/console-browserify/index.js which falls outside of the project directory.". Any Ideas?Studio
W
97

I think most the answers here would resolve your issue. However, if you don't need Polyfills for your node development, then I suggest using target: 'node' in your Webpack module configuration. This helped resolve the issue for me.

Here is some documentation on the answer: https://webpack.js.org/concepts/targets/

enter image description here

Wexford answered 21/2, 2021 at 20:15 Comment(5)
It works well for Node 16.*.*Gatehouse
doesn't work for node 14.0.0Dickens
this didn't worked for me it crashed completely my app, some error about bundlingHarrier
Resolve the errors but I got "require" is not defined in the browser console.Asylum
Worked well for Node v18.12.1Phasis
B
84

As per Web3 documentation:

If you are using create-react-app version >=5 you may run into issues building. This is because NodeJS polyfills are not included in the latest version of create-react-app.

Solution:

Install react-app-rewired and the missing modules

If you are using yarn:

yarn add --dev react-app-rewired crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer process

If you are using npm:

npm install --save-dev react-app-rewired crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer process

Create config-overrides.js in the root of your project folder with the content:

const webpack = require('webpack');

module.exports = function override(config) {
    const fallback = config.resolve.fallback || {};
    Object.assign(fallback, {
        "crypto": require.resolve("crypto-browserify"),
        "stream": require.resolve("stream-browserify"),
        "assert": require.resolve("assert"),
        "http": require.resolve("stream-http"),
        "https": require.resolve("https-browserify"),
        "os": require.resolve("os-browserify"),
        "url": require.resolve("url")
    })
    config.resolve.fallback = fallback;
    config.plugins = (config.plugins || []).concat([
        new webpack.ProvidePlugin({
            process: 'process/browser',
            Buffer: ['buffer', 'Buffer']
        })
    ])
    return config;
}

Within package.json change the scripts field for start, build and test. Instead of react-scripts replace it with react-app-rewired before:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

after:

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
},

The missing Nodejs polyfills should be included now and your app should be functional with web3.

If you want to hide the warnings created by the console:

In config-overrides.js within the override function, add:

config.ignoreWarnings = [/Failed to parse source map/];
Beaufort answered 26/2, 2022 at 20:54 Comment(7)
This helped I added the config-overrides file to my root and then called crypto in a js file in src folder. When I did that I got the error: Module not found: Error: You attempted to import /Users/username/abja/identity/node_modules/crypto-browserify/index.js which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.Plenary
its work for meBiysk
It doesn't work for me: Module not found: Error: Can't resolve 'process/browser' in '/Users/bartolini/workspace-osa/osa-web-ui/node_modules/axios/lib/defaults' Did you mean 'browser.js'? BREAKING CHANGE: The request 'process/browser' failed to resolve only because it was resolved as fully specifiedTed
Also got this but in another lib (dependency of react-markdown): Module not found: Error: Can't resolve 'process/browser' in '...\node_modules\uvu\node_modules\kleur' Did you mean 'browser.js'? BREAKING CHANGE: The request 'process/browser' failed to resolve only because it was resolved as fully specifiedOverhappy
Only thing that worked after hours(days?) of searching everywhere. This should be marked as the accepted answer IMOBuilt
in 2023 this worked for me, was a web3 project. Would caution that fixing this issue leads to other old issues, such as the wallet connect method being old too, so lots of intertwined dev and ux issuesCrookback
@Ted I got same 'process/browser' error and solve by adding config.module.rules.unshift({ test: /\.m?js$/, resolve: { fullySpecified: false, }, }); github.com/react-dnd/react-dnd/issues/3425Rhetorical
H
40

I faced this issue with create-react-app which by default gave me

"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"web-vitals": "^2.1.2"

I fixed it by just changing react-scripts to version 4.0.3.

Hudnall answered 19/12, 2021 at 4:20 Comment(5)
This worked for me. Its a temp solution, but successful for now.Luciana
The only thing that worked for me, thanks ! Nice temporary fix until it breaks, by which time there will hopefully be a more up-to-date solution.Garek
This worked for me as well, I don't have webpack integration in our app yet so this is the best solution for me.Downer
Downgrading to 4.0.3 worked for me as wellLustful
With react 18 i get 20 more vulnerabilities with 4.0.3 than 5.0.1Harrier
M
33

Looks like you've used the path package which is not included in webpack builds by default. For me, extending the webpack config like this helped:

{
  // rest of the webpack config
  resolve: {
    // ... rest of the resolve config
    fallback: {
      "path": require.resolve("path-browserify")
    }
  },
}

Also install path-browserify via npm install path-browserify --save-dev or yarn add path-browserify --dev if you're using yarn.

Merited answered 2/1, 2021 at 18:15 Comment(2)
If it will be shipped to the browser, should it be a dev dependency?Brana
@MMansour if you build your app as a webpack project and just ship the built artifacts, it shouldn't matter. Differentiation between dev and normal dependencies is only relevant if you publish your package to NPM, in which case consumers of your package will only install non-dev dependencies.Merited
M
25

You need React => v17 React scripts=> v5 webpack => v5

To Fix The Problem

1) Install

"fs": "^2.0.0",  // npm i fs
"assert": "^2.0.0",  // npm i assert
"https-browserify": "^1.0.0", // npm i https-browserify
"os": "^0.1.2", // npm i os
"os-browserify": "^0.3.0", // npm i os-browserify
"react-app-rewired": "^2.1.9", //npm i react-app-rewired
"stream-browserify": "^3.0.0", // stream-browserify
"stream-http": "^3.2.0", //stream-http

2) Creating config-overrides.js in root directory Image

3) Add configs to config-overrides.js

const webpack = require('webpack');
module.exports = function override(config, env) {
    config.resolve.fallback = {
        url: require.resolve('url'),
        fs: require.resolve('fs'),
        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'),
        buffer: require.resolve('buffer'),
        stream: require.resolve('stream-browserify'),
    };
    config.plugins.push(
        new webpack.ProvidePlugin({
            process: 'process/browser',
            Buffer: ['buffer', 'Buffer'],
        }),
    );

    return config;
}

3) Change packages.json

"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-app-rewired eject"
}

Problem solved :)

Midriff answered 14/1, 2022 at 15:20 Comment(6)
no need fir /browser in => os: require.resolve('os-browserify/browser'),Ogdan
this fix it for me.Presto
Worked for meee! Thank you so much. I was searching for a fix like hell for an hourReba
fs does'nt seem to be polyfilled. npm i fs does'nt seem to work,package is in security holding.Hersch
Docs for react-app-rewired say "Do NOT flip the call for the eject script"Uppermost
I tried this to use svgr directly in the browser, but it keeps complaining that os.homedir is not a function even though it uses the latest version of os-browserify. Sadly I cannot find any answer for my specific problem, but I guess it is kind of hacky anyway to try to use node apps this way.Fiddle
S
18

Create React App just released v5 which now implements Webpack v5. This is going to fully break many libraries which includes web3 as the required Node core library polyfills will be missing.

To resolve this quickly you can change this in your package.json:

"react-scripts": "^5.0.0"

To this

"react-scripts": "4.0.3"

After this:

rm -r node_modules

rm package-lock.json

npm install
Stefansson answered 23/1, 2022 at 8:30 Comment(2)
Unfortunately this solution leaves me with this frustrating circumstance: #70721556Muscadine
I've encountered the same scenario as Gus T Butt pointed out, but I'd prefer to degrade the react-scripts to 4.0.3 until this issue is fixed. As @chokshen mentioned in this thread[1] the fixed dependency version to the resolutions section of package.json works well "resolutions": { "//": "See github.com/facebook/create-react-app/issues/11773", "react-error-overlay": "6.0.9" }, my environment: Node: 16.14.2 react-scripts: 4.0.3 react: 17.0.2 [1]#70721556Ashliashlie
A
15

It happen with me while I reinstall the node modules my webpack current version is 5.38.1, I have fixed the issue with npm i path-browserify -D after installation you have to update your webpack.config.js resolve{} with fallback: {"fs": false, "path": require.resolve("path-browserify")} while not using "fs": false it show errors i.e: Module not found: Error: Can't resolve 'fs' in '/YOUR DIRECTORY ...' so don't forget to add it; with other stuff it look like:

module.exports = {
   ...
   resolve: {
    extensions: [".js", ".jsx", ".json", ".ts", ".tsx"],// other stuff
    fallback: {
      "fs": false,
      "path": require.resolve("path-browserify")
    }
  },
};

remove node property if it exist in your webpack.config.js file

Albinaalbinism answered 10/6, 2021 at 7:50 Comment(0)
P
11

Method 1

  • Open project/node_modules/react-scripts/config/webpack.config.js

  • In fallback add "crypto": require.resolve("crypto-browserify")

resolve: {
   fallback: {
       "crypto": require.resolve("crypto-browserify")
   }
} 
  • Install npm i crypto-browserify
  • Restart your app.

Above method doesn't work if you commit since we aren't node_modules

Method 2

  • Install patch-package: yarn add patch-package

  • Install the needed pollyfills.(do an initial build of your application and it will tell you.)

  • Modify node_modules/react-scripts/config/webpack.config.js. Here's an example. This is taken from Webpack's docs.

module.exports = {
  //...
  resolve: {
    fallback: {
      assert: require.resolve('assert'),
      buffer: require.resolve('buffer'),
      console: require.resolve('console-browserify'),
      constants: require.resolve('constants-browserify'),
      crypto: require.resolve('crypto-browserify'),
      domain: require.resolve('domain-browser'),
      events: require.resolve('events'),
      http: require.resolve('stream-http'),
      https: require.resolve('https-browserify'),
      os: require.resolve('os-browserify/browser'),
      path: require.resolve('path-browserify'),
      punycode: require.resolve('punycode'),
      process: require.resolve('process/browser'),
      querystring: require.resolve('querystring-es3'),
      stream: require.resolve('stream-browserify'),
      string_decoder: require.resolve('string_decoder'),
      sys: require.resolve('util'),
      timers: require.resolve('timers-browserify'),
      tty: require.resolve('tty-browserify'),
      url: require.resolve('url'),
      util: require.resolve('util'),
      vm: require.resolve('vm-browserify'),
      zlib: require.resolve('browserify-zlib'),
    },
  },
};
  • Don't add all of them, add only the ones you need.

Make sure you install the packages first before modifying the webpack config.

  • Run yarn patch-package react-scripts. This will generate a patch (this should be committed in your repo going forward).

  • Add a postinstall script to package.json: "postinstall": "yarn patch-package". Now, anytime, someone installs npm deps on this project, will get the patch you created in step 3 applied automatically.

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postinstall": "yarn patch-package"
  },
Pillory answered 4/3, 2022 at 5:44 Comment(2)
Method 1 is very bad. Never recommend changing something in node_modules!!Audun
Method 2 does not work for process. See other answers that use ProvidePlugin.Emileeemili
C
9

My solution for #VUE

const { defineConfig } = require('@vue/cli-service')
const webpack = require('webpack');
module.exports = defineConfig({
  configureWebpack: {
    plugins: [
      new webpack.ProvidePlugin({
        Buffer: ['buffer', 'Buffer'],
      }),
      new webpack.ProvidePlugin({
          process: 'process/browser',
      })
    ],
    resolve: {
      fallback: {
        "os": require.resolve("os-browserify/browser"),
        "url": require.resolve("url/"),
        "crypto": require.resolve("crypto-browserify"),
        "https": require.resolve("https-browserify"),
        "http": require.resolve("stream-http"),
        "assert": require.resolve("assert/"),
        "stream": require.resolve("stream-browserify"),
        "buffer": require.resolve("buffer")
      }
    }
  },

  transpileDependencies: [
    'vuetify'
  ]

})
Caravansary answered 17/3, 2022 at 20:42 Comment(3)
It saves me in my vue 2 projectLecce
What is this file?Auctorial
@CameronHudson it is vue.config.jsCaravansary
U
6

My environment is like this:

  • React => v17
  • React scripts=> v5
  • webpack => v5

To Fix The Problem follow the below instructions

1- Install below packages

yarn add fs assert https-browserify os os-browserify stream-browserify stream-http react-app-rewired

2- Create config-coverrides.js in Root dir of your project next to the package.json

add the below code to it:

const webpack = require('webpack');
module.exports = function override(config, env) {
    config.resolve.fallback = {
        url: require.resolve('url'),
        fs: require.resolve('fs'),
        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'),
        buffer: require.resolve('buffer'),
        stream: require.resolve('stream-browserify'),
    };
    config.plugins.push(
        new webpack.ProvidePlugin({
            process: 'process/browser',
            Buffer: ['buffer', 'Buffer'],
        }),
    );

    return config;
}

3- Change the packages.js like the below

  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },
Ulema answered 11/1, 2022 at 16:6 Comment(3)
Your clean explanation however, gives a memory issue when in CI/CD of Gitlab, it uses significantly more memory than without the react-app-rewired trick. At the end, I had to downgrade to react-scripts 4.0.3 againBurkitt
Of all those options, this was the only worked properly. Simply downgrading react-scripts to 4.0 on my scenario wasn't a solution since it was breaking all the Tailwind stuff that I am using.Tabina
The docs for react-app-rewired say "Do NOT flip the call for the eject script." in other words, leave "eject" as "react-scripts eject".Uppermost
C
5

npm install path-browserify and then try to change webpack configuration to include:

module.exports = {
    ...
    resolve: {
        alias: {
            path: require.resolve("path-browserify")
        }
    }
};
Chercherbourg answered 1/12, 2020 at 13:30 Comment(0)
A
5

I'm using create-react-app with craco, and I encountered the following errors when upgrading to webpack 5:

'buffer'


Module not found: Error: Can't resolve 'buffer' in '/Users/therightstuff/my-project/node_modules/safe-buffer'

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

This was resolved simply by installing the buffer package with npm install -D buffer.

'fs'


Module not found: Error: Can't resolve 'fs' in '/Users/therightstuff/my-project/node_modules/line-navigator'

This was resolved by setting a webpack fallback in the craco configuration craco.config.js:

module.exports = {
    style: {
        postcssOptions: {
            plugins: [
            require('tailwindcss'),
            require('autoprefixer'),
            ],
        },
    },
    webpack: {
        configure: (webpackConfig, { env, paths }) => {
            // eslint-disable-next-line no-param-reassign
            webpackConfig.resolve.fallback = {
                fs: false,
            };
            return webpackConfig;
        },
    },
}
Aurea answered 20/2, 2022 at 9:12 Comment(1)
fs: false, worked for me!! i used config-overrides.js though.Armin
S
2

you want to used in

const nodeExternals = require('webpack-node-externals');

add in webpack.config.js

target: "node",
devtool: "source-map",
externals: [nodeExternals()],
Snigger answered 15/4, 2021 at 10:31 Comment(2)
please take time to read this: stackoverflow.com/help/how-to-answerCenobite
for webpack 5: replace target: node by externalsPresets: { node: true },Asylum
P
2

This is happening with the new vue-cli upgrade (v5). In order to fix it (the empty modules way), you have to change vue.config.js this way:

configureWebpack: (config) => {
  config.resolve.fallback = {
    ...config.resolve.fallback,
    // Include here the "empty" modules
    url: false,
    util: false,
    querystring: false,
    https: false,
  };
}
Peerless answered 21/2, 2022 at 10:43 Comment(0)
C
2

I found a solution that worked for me:

  1. npm uninstall webpack
  2. delete the "package-lock.json" file
  3. npm install [email protected] --force
  4. include in the "package.json" file the following in your "scripts":
    "scripts": {
        "start": "SET NODE_OPTIONS=--openssl-legacy-provider && react-scripts start",
        "build": "SET NODE_OPTIONS=--openssl-legacy-provider && react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    }
    
Czechoslovak answered 19/6, 2022 at 12:24 Comment(1)
Finally. This one works for me. I only want to use dotenv, but man.. it hurtLandonlandor
E
2

All other answers are missing one important piece: how NOT to polyfill the node core modules. In case the error comes from some module in dependency of dependency of your dependency, which you actually do not need, you can quite safely ignore it. In that case, the most simple workaround is to add to your package.json these lines:

"browser": {
  "fs": false,
  "path": false,
  "os": false
}

And similarly for other core node modules if you need to ignore them.

This approach works great for frameworks where the actual webpack config is not directly accessible by default (like Angular).

I have found this solution when looking for a different error.

Elitism answered 8/2, 2023 at 23:3 Comment(0)
A
2

For those still doing configuration through react-app-rewired's config-overrides.js file, this will work:

config-overrides.js

const { override, addWebpackPlugin } = require('customize-cra')
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")

module.exports = override(addWebpackPlugin(new NodePolyfillPlugin()))

package.json

...
"dependencies": {
    ...
    "customize-cra": "^1.0.0",
    "node-polyfill-webpack-plugin": "^2.0.1"
  },

This will inject node-polyfill-webpack-plugin as a webpack 5 plugin.

Alkyd answered 2/5, 2023 at 18:36 Comment(0)
K
1
npm install assert --save

npm install buffer --save

For anyone facing similar issue, just install the missing modules. These modules are reported as missing because they are part of node.js, but are available separately also via the npm.

Kester answered 5/2, 2022 at 2:22 Comment(1)
Does not work. Just installing a module, does not cause it to be included and called, webpack excludes unused code.Burkitt
D
1

I got this error while imported Router from express import { Router } from 'express';

Resolved after correction import { Router } from '@angular/router';

Deathly answered 1/7, 2022 at 6:18 Comment(0)
T
1

Faced the same issue, here's a solution:

  1. Remove package-lock.json from the project folder and npm uninstall webpack
  2. Downgrade react-script from to 4.0.3
  3. Make sure package-lock.json is deleted/removed
  4. Install webpack using npm install [email protected]
  5. Finally, run npm install using the terminal
Trichloroethylene answered 20/7, 2022 at 13:56 Comment(0)
B
1

I tried this https://mcmap.net/q/82122/-i-tried-to-polyfill-modules-in-webpack-5-but-not-working-reactjs solution and it solved the problem form me.

simply run the following 2 commands

npm uninstall react-scripts
npm install [email protected]
Beneath answered 30/7, 2022 at 23:12 Comment(1)
Thanks @kennisnutz, this was the easiest fix for me. Just a small headache which I am just ignoring for now: I am using React 18.2 and after your suggested change my VSCode parser complains about import { useState } from "react"; "Parsing error: require() of ES Module gappscript\node_modules\eslint-scope\lib\index.js from gappscript\node_modules\babel-eslint\lib\require-from-eslint.js not supported. index.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules. Instead"Proselyte
Y
1

I had a React.js and Firebase app and it was giving the same error. I solved my issue by removing require('dotenv').config();. New React.js versions automatically handles loading packages like dotenv.

This polyfill error is not only with dotenv package but also with some other packages. So, if you have some loading statements as above, you can remove them and retry again.

Yaelyager answered 7/8, 2023 at 21:22 Comment(0)
D
0

My app threw the same error yesterday. I spent hours reading questions/answers here on SO and trying some. What has worked for me is this:

https://github.com/ChainSafe/web3.js#troubleshooting-and-known-issues

Demaggio answered 27/1, 2022 at 13:34 Comment(0)
W
0

If it's Twilio you use:

The Twilio module is not intended for use in client-side JavaScript, which is why it fails for your Angular application. Twilio uses your Account SID and your Auth Token, the use in the client side represents a risk; So the best is to use it on the server side and to use the API.

Wilde answered 3/2, 2022 at 23:41 Comment(0)
G
0

With create-react-app v17 and scripts 5.0.0 you need to add a fallback to your webpack.config.js and install 'process'.

   `module.exports = function (webpackEnv) {
      .........
      return {
       .........
      resolve: {
      ..........
      fallback: { "process": require.resolve("process/browser") },`
Glen answered 8/2, 2022 at 12:55 Comment(0)
C
0

Secret's answer very nearly worked for me (I don't have enough reputation yet to comment on there, sorry!)

After having followed the steps in their answer it then told me that because of the difference in required versions of eslint, I should add SKIP_PREFLIGHT_CHECK=true to a .env file in the project, so I just added it to my existing one.

It would then successfully build (finally!) But then I noticed, in Chrome at least, that I couldn't click on anything or even select any text. Turns out that there's still an Iframe over the top of everything that can be removed in Inspector. - This applies when running a dev build, npm run start, I am not sure if it does it on a production build.

I must say this sudden change IMO really hasn't been very well thought through!

Chockfull answered 16/2, 2022 at 10:19 Comment(0)
C
0

if you are using create-react-app with craco then configuration in craco.config.js should be like this:

module.exports = {
  webpack: {
      configure: {
        resolve: {
          fallback: {
            "path": require.resolve("path-browserify")
          },
        },
      },
    },
}
Clint answered 21/7, 2023 at 9:24 Comment(0)
H
0

If you're having this error on your react app, webpack.config.js would not help you override the webpack config. You have to use craco to solve this and then run your project with craco ie

    craco.config.js

     const path = require('path');
     module.exports = {
      webpack: {
       configure: {
        resolve: {
         fallback: {
          crypto: require.resolve('crypto-browserify'),
         },
        },
       },
      },
     };

Then you run your react app on craco ie

    package.json
 
    "scripts": {
     "start": "craco start",
     "build": "craco build",
    },
Headstall answered 27/1 at 15:56 Comment(0)
R
0

In case you're using create-react-app, you can use craco to expose webpack config and add this to craco.config.js:

module.exports = {
  webpack: {
    configure: (webpackConfig, { env }) => {
      webpackConfig.resolve.fallback = {
        http: false,
        https: false,
        //other stuff needs polyfill
      };
    }
  }
}

You could either do https: false or https: require('https-browserify') depends on your needs.

Rosabelle answered 30/1 at 0:32 Comment(0)
R
-1

my problem was that I was trying to use JSON.parse, then when I started writing , auto complete showed me json(note small letters) though I renamed it to JSON. when I pressed enter it automatically imported (import { json } from "express/lib/response";) it was the cause and I didn't notice it at all , later in development my app was crushing and it took me about six hours to note, since the app is quite big.

so if none of the above solutions work just see if you didn't import something .

Rhombus answered 2/6, 2022 at 18:53 Comment(0)
R
-1

I tried to follow as many solutions as I can. But Surprisingly none of them work for me. Except for the downgrade option. But that creates another problem. Framer motion was not working in that node version. So tried to follow the console log. After opening that I find out the stream was missing there. So Simply I install that dependency using (npm i stream). And fixed the problem. Maybe it's different for you. But just installing the missing dependency will solve the problem instead of writing a few more lines of code.

Rippy answered 28/4, 2023 at 22:31 Comment(0)
M
-2

ERROR : [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.

Answer: node_modules > react-scripts > config > webpack.config.js

Add in webpack.config.js file:

resolve: {
      fallback: { 
        "http": require.resolve("stream-http") ,
         "path": require.resolve("path-browserify") 
        },
}

Marjoriemarjory answered 2/1, 2022 at 5:18 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Slothful
S
-2

for me, I just removed an unused import called:

import res from "express/lib/response"

and it fixed it!

Syman answered 12/4, 2022 at 21:51 Comment(0)
H
-2

For me (using React => v17; React scripts=> v5; webpack => v5), a combination of solutions suggested by @Letton and @Richie Bendall worked along with another addition, i.e. to the package.json, the following packages had to be added and installed. Please also note that fs version "^2.0.0" throws an error, so changed to "0.0.1-security".

"assert": "^2.0.0", 
"https-browserify": "^1.0.0", 
"os": "^0.1.2",
"os-browserify": "^0.3.0",
"react-app-rewired": "^2.1.9",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
"fs":"^0.0.1-security",
"crypto-browserify": "3.12.0",
"buffer":"^6.0.3",
"node-polyfill-webpack-plugin": "^2.0.1"

After installation of these, executing the remaining steps, i.e. adding config-overrides.js to the root directory and changing scripts content in package.json from react-scripts to react-app-rewired fixed the problem.

Hydrostatic answered 30/8, 2022 at 16:43 Comment(0)
S
-2

Though this answer doesn't directly deal with the polyfill but sometimes one should evaluate if you really need a library which needs a polyfill at first place. We shouldn't reinvent the cycle but at the same time this comes with some disadvantages particularly when you are trying to migrate from one version to another. I faced a very similar issue while upgrading from Angular 7 to 12. In my case, in one of the components we were using util.isArray. The solution was to replace util.isArray to Array.isArray and remove the util import from the component. This not only helped in getting rid of the library but also ensured that we wouldn't have to polyfill.

Straub answered 16/5, 2023 at 10:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.