DEV Community

sand4rt
sand4rt

Posted on • Updated on

How to configure import aliases in Vite, TypeScript and Jest

Most people have seen them, those immensely long import paths like the example below:

import module from "../../../../../modules/module.ts";
Enter fullscreen mode Exit fullscreen mode

To improve this, you can use import aliases and make it look like the example
below:

import module from "@/modules/module.ts";
Enter fullscreen mode Exit fullscreen mode

The benefit of this is readability and that you can move files and folders to sub or parent directories without changing the import paths.

Tools like Vue CLI are supporting this out-of-the-box, but if you want to use the new blazing-fast build tool Vite, you'll need to (at the time of writing)
configure it manually. I've included TypeScript and Jest because they are often used in combination.

For this to work, all tools need to know that import aliases are used by modifying each tool's configuration file.

Vite has a configuration file called vite.config.ts and by adding the resolve object Vite will know that import aliases are being used:

// vite.config.ts
import { defineConfig } from "vite";
import path from "path";

export default defineConfig({
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

By adding a paths object to the compilerOptions inside the tsconfig.json like the example below TypeScript will also know that import aliases are being used:

// tsconfig.json
{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

At last Jest knows that aliasses are being used by adding the moduleNameMapper to the jest.config.ts configuration file like the code below:

// jest.config.ts
module.exports = {
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  },
};
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
barryschutte profile image
Barry Schutte

Thank you so much!

Collapse
 
verbindingsfout profile image
Tico Raaphorst • Edited

Import aliases are a general good addition to a growing project.