How to resolve the "Module not found: react-refresh/runtime.js falls outside of src/" error in a React application?
Hello! If you are also encountering the error "Module not found: react-refresh/runtime.js falls outside of src/" while trying to build your React application, don't worry! This error is usually due to the presence of invalid paths in Webpack configuration or during the use of react-refresh. Let's take a look at how to fix this issue.
The first step to resolving this issue is to ensure that all dependencies are correctly installed and the versions in use are compatible. For this reason, before anything else, make sure that the packages in node_modules are up-to-date. You can do this by running the command npm install
.
Next, we should check the Webpack configuration file. It may be necessary to review its paths and configurations. Usually, this error occurs because the Webpack configuration has trouble finding JavaScript files that exist. Ensure that the source files (src) are located in the correct directory.
Also, if you are using other tools like Babel or other build tools, maintaining the correct relationship between these tools and Webpack is very important to ensure that your files are built correctly.
The solution to the problem could involve using react-refresh
, which requires you to ensure that this package is properly installed and configured in Webpack. If you are using CRA (create-react-app), check how this package is configured in the CRA Webpack configuration file.
Now, let’s look at an example of a proper Webpack configuration that fixes this error:
{
"resolve": {
"alias": {
"react-refresh/runtime": require.resolve("react-refresh/runtime")
}
},
"module": {
"rules": [
{
"test": /\.js$/,
"exclude": /node_modules/,
"use": [
{
"loader": "babel-loader",
"options": {
"plugins": [require.resolve("react-refresh/babel")]
}
}
]
}
]
}
}
-- By using the resolve
alias, we can introduce the path react-refresh/runtime
to Webpack so that it can locate it.
-- The JavaScript code that needs to be reviewed during the build process should be identified in the "test" section. Here, all files of `*.js` are identified.
-- The "exclude" section specifies that none of the files inside node_modules
should be checked.
-- By assigning babel-loader
as the "loader", we ensure that the files will be transpiled by Babel during the build process.
-- "plugins": [require.resolve("react-refresh/babel")]
is a key part that enables support for the React feature, allowing hot reloading of your components.