DEV Community

Cover image for Make Pathing Easier with Aliases in SvelteKit
Brittney Postma
Brittney Postma

Posted on • Edited on • Originally published at codingcat.dev

Make Pathing Easier with Aliases in SvelteKit

UPDATE June '22:
SvelteKit Alias Docs were updated with an improved way of configuring aliases. Aliases can now be configured as top level under the kit property in the svelte.config.js file. This article is now updated to reflect this change.

const config = {
  kit: {
    alias: {
      $components: 'src/components',
      $utils: 'src/utils'
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

If you haven't heard about SvelteKit yet, go checkout the beautiful site over at kit.svelte.dev. SvelteKit is a component framework similar to React and Vue with one key difference, there is no virtual DOM. Svelte is a compiler that builds itself away into a sleek and fast end user experience. If you haven't tried Svelte or SvelteKit before, you can check out my quick intro tutorial where we build a blog in 30 minutes 🤯

Links:

TLDR: To setup an alias add the following lines to the svelte.config.js. For the code editor you are using to understand the alias, we also need to add to the jsconfig.json paths with the aliases you want to create.

//svelte.config.js
import path from 'path'
const config = {
    kit: {
        alias: { 
            '@components': path.resolve('./src/lib/components'),
                    '@lib': path.resolve('./src/lib'),
                    '@utils': path.resolve('./src/lib/utils')
                }
            }
        }
    },
}
export default config
Enter fullscreen mode Exit fullscreen mode
// jsconfig.json
{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
             // name and path to aliases
            "@components": ["src/lib/components"],
            "@lib": ["src/lib"],
            "@utils": ["src/lib/utils"]
        }
    },
    "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}
Enter fullscreen mode Exit fullscreen mode

Default Starter

To start a new SvelteKit project run npm init svelte@next app-name into the terminal where you want the folder to live. Change directory into your new app, cd app-name and run npm i to install the dependencies. Out of the box SvelteKit provides a $lib alias setup for the src/lib folder and a number of modules are available from $app and $service-worker. Outside of those, it is up to us to set up our own aliases and preferences on how to use them. These all use the $ syntax to use it, however, we are able to change the lib folder to @ or other symbol if preferred.

Change default alias

To update the default $lib alias to @lib, we need to tell vite that we want to use it by updating the svelte.config.js and the alias will work in our application. For the code editor to understand the alias, we need to edit the jsconfig.json file. Inside the svelte.config.js by default we see this setup.

/** @type {import('@sveltejs/kit').Config} */
const config = {
  kit: {
    // hydrate the <div id="svelte"> element in src/app.html
    target: '#svelte',
  },
}

export default config
Enter fullscreen mode Exit fullscreen mode

Inside of the kit property, we need to add a an alias property to hold the aliases we are setting up. I prefer the @ symbol rather than the default $ and will show how to setup the @lib, @components, and @utils aliases. We need to import the included path module from node at the top and add the alias property under the kit property. The new svelte.config.js will look like this.

//svelte.config.js
import path from 'path'
const config = {
    kit: {
        alias: { 
            '@components': path.resolve('./src/lib/components'),
                    '@lib': path.resolve('./src/lib'),
                    '@utils': path.resolve('./src/lib/utils')
                }
            }
        }
    },
}
export default config
Enter fullscreen mode Exit fullscreen mode

Next, we also need to set them up inside the jsconfig.json file. By default that looks like this.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
  // here is the default $lib setup by SvelteKit
      "$lib/*": ["src/lib/*"]
    }
  },
  "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the default $lib is added to this config already. We need to update that and add the paths for our other two aliases. The updated file will look like this.

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@components": ["src/lib/components"],
            "@lib": ["src/lib"],
            "@utils": ["src/lib/utils"]
        }
    },
    "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}
Enter fullscreen mode Exit fullscreen mode

Under paths we have added the @components, updated the $lib to @lib, and added @utils with the corresponding paths.

Using the aliases

Now we need to use the aliases inside of a file. The skeleton starter doesn't come with any folders outside of the routes folder for the routes of the application. If you chose this option, you can simply add the lib folder inside of the src folder to use the @lib alias. The other paths and aliases we setup are nested inside the lib folder. Add a components folder and utils folder inside of the lib folder. The folder structure should look like this.

src
  - lib
    - components
    - utils
  - routes
Enter fullscreen mode Exit fullscreen mode

Now any files created inside of lib, components, or utils can be imported using the alias rather than having to type out the absolute path, like so.

<script>
import FileName from '@lib/FileName.js`
import ComponentName from '@components/ComponentName.svelte'
import UtilName from '@utils/UtilName.js`
</script>
Enter fullscreen mode Exit fullscreen mode

And that's it 🥳 now you can use all of the aliases we created or create more of your own. I'm @brittneypostma on Twitter if you have more questions or just want to chat about Svelte 😃 Cheers!

Top comments (7)

Collapse
 
blindfish3 profile image
Ben Calder • Edited

Thanks - this was useful.
If you're using Storybook, you'll also have to define the aliases in that context. This issue covers some possible options to achieve that. The following worked for me:

.storybook/main.js

const path = require('path');

module.exports = {
  // existing config,
  webpackFinal: async (config) => {
    config.resolve.alias['@lib'] = path.resolve(__dirname, '../src/lib')
    config.resolve.alias['@components'] = path.resolve(__dirname, '../src/lib/components')
    config.resolve.alias['@utils'] = path.resolve(__dirname, '../src/lib/utils')

    return config;
  }
}
Enter fullscreen mode Exit fullscreen mode

There are some suggestions on how to avoid duplicating the aliases; but I didn't have any luck getting those to work.

edit: if you're using storybook your intent may be to deploy a component library. In that case don't use aliases; since these will break when the ./src/lib contents are included in your package. Maybe there's a way to output the full path when packaging the library; but otherwise it's safer to just use relative links.

Collapse
 
nickytonline profile image
Nick Taylor • Edited

Storybook 6.5 has the Vite builder now, so you’ll still need to have a config in main for the aliases, but it shouldn’t look too different from the config for aliases in Svelte. You can probably even have the alias config separately and import it into the Svekte config and main.js so you don’t need to duplicate it. See storybook.js.org/docs/react/builde...

Collapse
 
louislietaer profile image
Louis Lietaer

Hi Brittney, thanks for the post.

I have a question : is it possible to affect an alias value to variable ?

const mypath = '@lib/' not working of course

Collapse
 
sashko profile image
Oleksandr

Now you don't need to include "path.resolve()" before a path in the "svelte.config.js" file.

Collapse
 
psypher1 profile image
James 'Dante' Midzi

Thank you for this. Could please point me to where the path.resolve is explained. I can't find it in the docs

Collapse
 
nickytonline profile image
Nick Taylor

Great post! I’ve only ever used aliases in webpack. It makes sense that they’d offer this in other bundlers.

Collapse
 
fvilches17 profile image
Francisco Vilches

Thanks!