Home > Web Front-end > JS Tutorial > How Can I Import Assets from Outside the `src` Directory in Create React App?

How Can I Import Assets from Outside the `src` Directory in Create React App?

Mary-Kate Olsen
Release: 2024-11-27 17:32:11
Original
454 people have browsed it

How Can I Import Assets from Outside the `src` Directory in Create React App?

Overcoming the create-react-app Import Restriction Outside the Src Directory

When utilizing create-react-app, accessing assets such as images from folders outside the src directory can lead to the "Module not found" error. This restriction is inherent to create-react-app to maintain a clear project structure and ensure code security.

Reason for Restriction

The ModuleScopePlugin implemented in create-react-app enforces the restriction that relative imports from the app's src directory should not extend beyond it. This ensures that assets remain within the project's established boundaries.

Unofficial Solutions

Although the official stance is that this restriction cannot be disabled without ejecting from create-react-app, several unofficial solutions exist. However, ejecting comes with the risk of losing access to future updates and features.

  • Rewire: This tool allows for programmatic modification of the webpack config without ejecting, but removing the ModuleScopePlugin plugin is strongly discouraged.
  • React-app-alias: A better approach involves adding fully functional directories analogous to src that are also protected by ModuleScopePlugin.

Recommended Approach

Instead of importing from the public folder, it is advisable to place assets in the src folder. This offers several benefits:

  • Optimal package download size
  • Improved loading efficiency due to webpack's optimized chunk loading
  • Consistent asset availability via a single URL

By adhering to these guidelines, developers can avoid the import restriction and maintain the integrity and performance of their applications built with create-react-app.

The above is the detailed content of How Can I Import Assets from 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