Home > Web Front-end > JS Tutorial > body text

How to Import Assets Outside the `src` Directory in Create React App?

Linda Hamilton
Release: 2024-11-21 02:59:14
Original
718 people have browsed it

How to Import Assets Outside the `src` Directory in Create React App?

How to Handle Import Restrictions Outside of Src Directory in Create-React-App

In Create-React-App, importing files from outside the src directory is restricted. This limitation ensures that source files remain within the designated folder for better organization and prevents unnecessary imports.

If you encounter the following error message:

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.
Copy after login

It means you're attempting to import an image from outside the src directory. Several approaches can address this issue:

1. Move Assets to the Src Directory

Move the image file into the src directory to allow it to be imported. This ensures all essential files reside within the designated source folder.

2. Use URLs for Public Folder Assets

Instead of importing from the public folder, use absolute or relative URLs to access the image from the public folder directly. This approach avoids the import restriction and allows you to access assets from outside the src directory.

Important Note: It's crucial to avoid importing from the public folder directly, as this can lead to duplicate assets in the build and affect the optimal loading efficiency of the application. Importing from the src folder ensures that webpack effectively bundles the files, optimizing their size and loading speed.

The above is the detailed content of How to Import Assets Outside the `src` Directory in Create React App?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template