Evgenii Vedegisthoughts about software development

Getting rid of relative paths with webpack aliases

Date published: August 03, 2021

Files structure meme

Getting rid of relative paths and make your structure of project better with webpack and aliases. It's works perfect for react.js, vue.js and native js development.

Alias - Allows you to specify aliases that can be used in your projects.

Files structure react

When you import some component from large project you have a problem like looking for a needle in a haystack. Alias saves you from this crap.

Without aliases:

import Button from '../../../controls/button'

With aliases:

import Button from 'controls/button'

Aliases setup

Webpack config, we find something like this:

resolve: {
  modules: ['node_modules', paths.appNodeModules].concat(
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean),
  ),
  ...
}

In the array modules, add this value path.resolve ('./src') to the beginning or at the end.

Result should be like this:

modules: ['node_modules', paths.appNodeModules, path.resolve('./src')]

Configuring aliases for Storybook

For setup aliases with Storybook use it:

resolve: {
    // for react: '.js', '.jsx'
    // for vue: '.js', '.vue'
    // for native: '.js'
    extensions: ['.js', '.jsx'],
    alias: {
        app: path.resolve(__dirname, '../src/app')
    }
}

If you don't have the app folder or your application in src simply remove /app


© Copyright 2021, Evgenii Vedegis