Create an alias for a React component

Assume the following folder structure:

├── src
|   ├── app.js
|   ├── index.js
|   ├── assets
|   |   ├── images
|   |   |   ├── picture.jpg

You can import the picture in React as:

import picture from './assets/images/picture.jpg'
// app.js

You can also define an alias and import it as:

import picture from '@images/picture.jpg'
// app.js

An alias allows you to simplify imports in projects with several (sub)folders. To create aliases, you'll need to eject your React app. Ejecting an app allows to manipulate config files like webpack.config.js, and it's an irreversible action.

  1. Eject the app:
npm run eject
  1. Modify webpack.config.js:
resolve: {
    alias: {
        '@images': path.resolve(__dirname, '../src/assets/images/'),

Important: to create an alias, the folder should be inside React's src. Otherwise, you'll get an error.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.