The create-react-app imports restriction outside of src directory

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.

./src/components/website_index.js Module not found: You attempted to
import ../../public/images/logo/WC-BlackonWhite.jpg which falls
outside of the project src/ directory. Relative imports outside of
src/ are not supported. You can either move it inside src/, or add a
symlink to it from project’s node_modules/.

import logo from '../../public/images/logo_2016.png';
<img className="Header-logo" src={logo} alt="Logo" />

I have read many things saying you can do an import to the path but that is still not working for me. Any help would be greatly appreciated. I know there are many questions like this but they are all telling me to import logo or image so clearly I am missing something in the big picture.

Answer

This is special restriction added by developers of create-react-app. It is implemented in ModuleScopePlugin to ensure files reside in src/. That plugin ensures that relative imports from app’s source directory don’t reach outside of it.

You can disable this feature (one of the ways) by eject operation of create-react-app project.

Most features and its updates are hidden into the internals of create-react-app system. If you make eject you will no more have some features and its update. So if you are not ready to manage and configure application included to configure webpack and so on – do not do eject operation.

Play by the existing rules (move to src). But now you can know how to remove restriction: do eject and remove ModuleScopePlugin from webpack configuration file.


Instead of eject there are intermediate solutions, like
rewire which allows you to programmatically modify the webpack config without eject. But removing the ModuleScopePlugin plugin is not good – this loses some protection and does not adds some features available in src.

The better way is to add fully working additional directories similar to src. This can be done using react-app-rewire-alias


Do not import from public folder – that will be duplicated in the build folder and will be available by two different url (or with different ways to load), which ultimately worsen the package download size.

Importing from the src folder is preferable and has advantages. Everything will be packed by webpack to the bundle with chunks optimal size and for best loading efficiency.