How to add $dirname import shortcuts to Svelte + Vite
June 6, 2021
When I start a new project with Svelte and Vite, the first thing I do is set up aliases to reference important folders in my project. This keeps me out of what's called "import hell":
// Before
import Foo from '../../../../components/Foo.svelte'
// After
import Foo from '$lib/Foo.svelte'
In this post, we'll create two aliases, but you can add as many as you'd like.
$lib
- for referencing components (some people call this$components
)$utils
- for referencing utility functions
First, you'll need to add resolve.alias
to vite.config.js at the root of your project:
// vite.config.js
import { defineConfig } from 'vite'
import svelte from '@sveltejs/vite-plugin-svelte'
import path from 'path'
export default defineConfig({
plugins: [svelte()],
resolve: {
alias: {
$lib: path.resolve('./src/lib'),
$utils: path.resolve('./src/utils')
}
}
})
Second – and this part is optional but I recommend it – add paths
to the compilerOptions
your jsconfig.json file:
// jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"$lib/*": ["src/lib/*"],
"$utils/*": ["src/utils/*"],
"$stores/*": ["src/stores/*"],
"$assets/*": ["src/assets/*"]
}
},
// ...
}
This enables some nice IDE autocompletion and hinting features. I've found these to work surprisingly well with VS Code!
And that's all there is to it. Happy Svelting!