Most of the time when you are building a react project that is slight larger it starts giving an error of heap memory and we are unable to build the project.
I cam across the same issue and I was trying to sort it out and following solution worked. I am going to explain step by step how to resolve it.
We are going to use the CRACO for building the project instead of the default react method building the project
npm install --save-dev @craco/craco
After you install the CRACO then Create craco.config.js in your project
module.exports = {
webpack: {
configure: (webpackConfig, { env, paths }) => {
// Remove CSS minimizer completely
webpackConfig.optimization.minimizer = webpackConfig.optimization.minimizer.filter(
(minimizer) => !minimizer.constructor.name.includes('CssMinimizer')
);
// Disable source maps for CSS
webpackConfig.module.rules.forEach(rule => {
if (rule.oneOf) {
rule.oneOf.forEach(oneOfRule => {
if (oneOfRule.test && oneOfRule.test.toString().includes('css')) {
oneOfRule.use = oneOfRule.use.map(use => {
if (use.loader && use.loader.includes('css-loader')) {
return {
...use,
options: {
...use.options,
sourceMap: false
}
};
}
return use;
});
}
});
}
});
return webpackConfig;
},
},
};
the last step is to update the run scripts of your react project in the package.json to the one below
{
"scripts": {
"start": "craco start",
"build": "cross-env NODE_OPTIONS=--max-old-space-size=8192 craco build",
"build:large": "cross-env NODE_OPTIONS=--max-old-space-size=16384 craco build",
"test": "craco test",
"eject": "react-scripts eject"
}
}
Now when we run the npm run build command it will create the build folder without any error.
