DEV Community

Vita
Vita

Posted on

3 3

Using aliases in webpack

Last thing you want to see in your project's imports is ugly stuff like this
pic

Because this is a feature I use with some frequency, but not frequently enough that I remember the pattern when I need it, I wrote this article as my own memo.

  1. Change settings for webpack's config - using eslint-import-resolver-alias
  resolve: {
    alias: {
      '@ui': path.resolve(__dirname, 'src/components/ui'),
      '@shared': path.resolve(__dirname, 'src/shared'),
    },
    modules: [path.join(__dirname, 'src'), 'node_modules'],
    extensions: ['.js', '.jsx'],
  },
Enter fullscreen mode Exit fullscreen mode
  1. Change VSCode settings so Intellisense won't break
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": false,
    "baseUrl": ".",
    "jsx": "react",
    "paths": {
      "@ui/*": ["./src/components/ui/*"],
      "@shared/*": ["./src/shared/*"]
    }
  },
  "exclude": ["node_modules"]
}
Enter fullscreen mode Exit fullscreen mode
  1. Replace everything using a regexp. Example:
/'.*/shared/g
Enter fullscreen mode Exit fullscreen mode

or, if there's a simpler case

(\s)from(.*)shared/
Enter fullscreen mode Exit fullscreen mode

(whitespace is important so it won't count in files which have a "from" ending)

  1. And then pretty it up with linter autofixer.

Much better.
pic

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay