How to configure import aliases in Vite, TypeScript and Jest

by Sander — 2 minutes

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

import module from "../../../../../modules/module.ts";

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

import module from "@/modules/module.ts";

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"),
    },
  },
});

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

// tsconfig.json
{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src"]
    }
  }
}

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",
  },
};

meerdivotion

Cases

Blogs

Event