The more I work in React, the more I love it. It's a very mature framework that is immensely popular. While working with the Vue CLI, there was one feature I really appreciated: a default alias for the src directory. Having a Webpack alias for a commonly referenced directory eliminates fragile relative paths, produces cleaner code, and is much easier to read. Let's dive in.
Importing Without an Alias#
Let's look at how messy imports get without an alias. Imagine that SomeComponent.jsx is nested deep within the directory structure and needs to import AnotherComponent.jsx from a few levels up.
import React, { Component } from 'react';
import AnotherComponent from './../../../../../components/anotherComponent/AnotherComponent';
import ProfileImage from './../../../../../../assets/profile.jpg';
class SomeComponent extends Component {
render() {
return (
<div>
<img src={ProfileImage} alt="My profile image!" />
<AnotherComponent />
</div>
);
}
}
export default SomeComponent;
Those relative paths are ugly — but more importantly, they're fragile. Move a component up a level and all its dependencies break. Failed to compile.
Importing With a Webpack Alias#
import React, { Component } from 'react';
import AnotherComponent from '@/components/anotherComponent/AnotherComponent';
import ProfileImage from '@/assets/profile.jpg';
class SomeComponent extends Component {
render() {
return (
<div>
<img src={ProfileImage} alt="My profile image!" />
<AnotherComponent />
</div>
);
}
}
export default SomeComponent;
Much better. The code is cleaner and, since we're using absolute paths, far less fragile.
How to Set Up Webpack Aliases in create-react-app#
This assumes you're using create-react-app, React's CLI. To configure a Webpack alias, you'll need to eject first so you have direct access to the config files.
- Run:
npm run eject - Open
config/webpack.config.dev.js - Find the
aliasobject - Add the following:
'@': path.resolve('src')
Your alias object should look something like this:
alias: { '@': path.resolve('src'), 'react-native': 'react-native-web' }
You can also create aliases for commonly used node_modules. For my projects, I usually add one for Bulma, the Flexbox CSS framework. Note: the alias doesn't have to start with @ — it can be anything you want.
'bulma': path.resolve('node_modules/bulma/css/bulma.css')
Then in any component, import it like any other package:
import Bulma from 'bulma';
Wrapping Up#
Webpack aliases are a small configuration change with a big payoff. Cleaner imports, more resilient code, and less time hunting down broken relative paths every time you restructure a directory. If you're working on a React project of any meaningful size, it's worth setting up early.
