DEV Community

Vita
Vita

Posted on

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

Top comments (0)