Getting rid of relative paths in imports using webpack alias

Alankar Anand
2 min readMay 16, 2019

--

No more “import config from ‘../../../utilities/configs’ ”

Kilimanjaro

React emphasises on modular code and component architecture. Dividing the app into presentational and container components makes the code more readable and also reusable. One thing that I have found helpful while using components is using webpack alias to import components.

Traditionally we import a component by mentioning the directory using combination of dots and slashes. The problem with this approach is that this is very error prone. In case you move one file from one place to another, you may have to change ( manually, based on the IDE you are using) all the imports to point to the new location.

Webpack provides a way to solve this problem. You can use alias to point to the components and use that alias everywhere in the project.

How it works ?

You can add an alias under resolve option provided by web pack in the web pack config file.

resolve: {
alias: {
Utilities: path.resolve(__dirname, ‘src/utilities/’),
Templates: path.resolve(__dirname, ‘src/templates/’)
}
}

So when importing from these folders you can use absolute paths like ‘Utilites/<component>’ to fetch the component.

// Instead of using relative paths
import config from ‘../../../utilities/configs'
// Now you can do
import config from ‘Utilities/configs'

Also, in case you change the location of a file or folder, you only need to update the alias to point to the new location.

For more info: https://webpack.js.org/configuration/resolve/

Checkout my other posts:

  1. Why is customer acquisition a wrong metric to measure startup’s growth.
  2. What’s the difference between super and super(props) in ES6.
  3. CurrentTarget vs Target in Js.
  4. A brief introduction of Node, React and NPM.
  5. Named export vs Default export in ES6.

--

--