Skip to main content

A Better Way to Alias Import in JavaScript / TypeScript

Published on Nov 15, 2021

Alias imports is a Webpack feature in JavaScript that allows you to declare a relative import path that you can then call by the alias name you declared.

With alias imports, you can declare the src/components directory as @components, then calling it anywhere within your project using that import alias.

This solves the issue of having to import a file from within a deeply nested project structure which results in something like this: ../../../components/Hello.tsx

However, rather than manually declaring alias imports on a per-directory basis, you should just declare an alias import for the src directory using the tilde sign ~, then calling any directory within src like ~/components, ~/utilities, ~/assets, etc...

The reason why I chose the ~ tilde symbol instead of the @ symbol was to avoid confusion with NPM namespaces like @org/package-name and because tilde refers to the home directory of where it's being called from. If you accidentally declare the same @org alias, it may break your project!

© 2019-2021 by Daniel Ramirez

Made with
Love
in Arizona