The Create-React-App Imports Restriction Outside of Src Directory

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

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.

There is no official way to disable this feature except using eject and modify webpack config.

But, most features and its updates are hidden into the internals of create-react-app system. If you make eject you will have no more new 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 assets to src or use based on public folder url without import.


However instead of eject there are much unofficial solutions, based on
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. ModuleScopePlugin is designed to support multiple folders.

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


Anyway do not import from public folder - that will be duplicated in the build folder and will be available by two different url (and 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.

ReactJS import component outside src/ directory

Got to your A-app node_modules folder and run the following

ln -s ../../../src/components/Dashboard ./app-b-dashboard

After creating the following symbolic link in your node_modules folder you can import in you A-app

import Dashboard from 'app-b-dashboard/container'

The names might be different depending on the specific layout of your project. This is my best guess based on the info you provided.

Module not found: You attempted to import which falls outside of the project src/ directory. Relative imports outside of src/ are not supported

You should use /images/img-2.jpg/ to refer to the folder. The reason is that you are using create-react-app to create this React app. When being bundled the app will be located in the public folder. Read this other question where it mentions the same issue.



Related Topics



Leave a reply



Submit