Assume the following folder structure:
terminal├── src | ├── app.js | ├── index.js | ├── assets | | ├── images | | | ├── picture.jpg
You can import the picture in React as:
javascriptimport picture from './assets/images/picture.jpg' // app.js
You can also define an alias and import it as:
javascriptimport 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.
terminalnpm run eject
webpack.config.js
:javascriptresolve: { 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.