Path Aliases in TypeScript (with Vite or Webpack bundlers)



This content originally appeared on DEV Community and was authored by Shane McGowan

A Path Alias in TypeScript lets us simplify our import paths with an alias

So rather than doing ugly relative imports like this:

import { User } from '../../model/user'

We can do something like clean like this:

import { User } from '@model/user'

To set this up, go to your tsconfig.json and add the following under compilerOptions

// tsconfig.json
{
  "compilerOptions": {
    // ...some other compiler options

    "paths": {
      "@model/*": [
        "./src/model/*"
      ],
    },
  },
}

To see this change come into affect in your editor, restart your TypeScript language server.

Path Aliases with a bundler

If you are using a bundler you will also need to let your bundler know about your new alias. I won’t give an example for every bunlder out there but here is how to do it in either Vite or Webpack.

Vite

In your vite.config.js add the following (or create a vite.config.js file in the root of your project (beside your package.json) if you haven’t created one yet.

import { defineConfig } from "vite";
import path from "path";

export default defineConfig({
  resolve: {
    alias: {
      "@model": path.resolve(__dirname, "./src/model"),
    },
  },
});

Webpack

Basically the same as your Vite config above (probably intentionally similar), add the following to your webpack config file

{
  // ... some other config here
  resolve: {
    alias: {
      '@model': path.resolve(__dirname, "./src/model"),
    },
    extensions: ['.ts', '.js'], // I can't remember if this is needed so remove it if it isn't
  },
}


This content originally appeared on DEV Community and was authored by Shane McGowan