I am using create-react-app. I am trying to call an image from my public folder from a file inside my src/components
. I am receiving this error message.
the best solution is to fork react-scripts
, this is actually mentioned in the official documentation, see: Alternatives to Ejecting
Remove it using Craco:
module.exports = {
webpack: {
configure: webpackConfig => {
const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
({ constructor }) => constructor && constructor.name === 'ModuleScopePlugin'
);
webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);
return webpackConfig;
}
}
};
This restriction makes sure all files or modules (exports) are inside src/
directory, the implementation is in ./node_modules/react-dev-utils/ModuleScopePlugin.js
, in following lines of code.
// Resolve the issuer from our appSrc and make sure it's one of our files
// Maybe an indexOf === 0 would be better?
const relative = path.relative(appSrc, request.context.issuer);
// If it's not in src/ or a subdirectory, not our request!
if (relative.startsWith('../') || relative.startsWith('..\\')) {
return callback();
}
You can remove this restriction by
eject
then remove ModuleScopePlugin.js
from the directory.const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
from ./node_modules/react-scripts/config/webpack.config.dev.js
PS: beware of the consequences of eject.
I think Lukas Bach solution to use react-app-rewired in order to modify webpack config is a good way to go, however, I wouldn't exclude the whole ModuleScopePlugin but instead whitelist the specific file that can be imported outside of src:
config-overrides.js
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const path = require("path");
module.exports = function override(config) {
config.resolve.plugins.forEach(plugin => {
if (plugin instanceof ModuleScopePlugin) {
plugin.allowedFiles.add(path.resolve("./config.json"));
}
});
return config;
};
You need to move WC-BlackonWhite.jpg
into your src
directory. The public
directory is for static files that's going to be linked directly in the HTML (such as the favicon), not stuff that you're going to import directly into your bundle.