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
. I am covering those specifically as I currently have active TypeScript based projects using both and don't care to migrate the Webpack one to Vite as Webpack still works fine.
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.
// vite.config.js
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.js
file.
// webpack.config.js
const path = require('path');
module.exports = {
// ... 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
},
}
👋 Checkout more of my stuff at shanemcgowan.com or feel free to reach out to me at my email hi@shanemcgowan.com 👋