DEV Community

Sibtain Jafferi
Sibtain Jafferi

Posted on

Absolute Paths in Svelte

In order to avoid lengthy relative path imports like this:

import Component  from "../../../../components/Component.svelte";
Enter fullscreen mode Exit fullscreen mode

Gross.

@rollup/plugin-alias to the rescue!

Start by installing it into dev dependencies:

yarn add -D @rollup/plugin-alias

Next, add the plugin into your rollup config.

Note: Make sure to add it to both server and client bundles if you're using SSR in Svelte.

// rollup.config.js
import alias from '@rollup/plugin-alias';

const aliases = alias({
  resolve: ['.svelte', '.js'], //optional, by default this will just look for .js files or folders
  entries: [
    { find: 'components', replacement: 'src/components' },
    { find: 'metadata', replacement: 'src/metadata' },
    { find: 'util', replacement: 'src/util' },
  ]
});

...

export default {
  ...
  plugins: [
    aliases
  ]
  ...
}
Enter fullscreen mode Exit fullscreen mode

Now we can do:

import Component from "components/Component.svelte";
Enter fullscreen mode Exit fullscreen mode

yay!

Top comments (5)

Collapse
 
ozzythegiant profile image
Oziel Perez

Notes: resolve property no longer exists on this plugin. If you wish to use something like "@/components" in your imports, the specific way to define this is:

alias({
    entries: [
        { find: '@', replacement: "/src" },
    ]
})
Enter fullscreen mode Exit fullscreen mode

It seems the replacement path is based on the project's root folder

Collapse
 
sherlockcodes profile image
Lucas Miguel

It works for me. But somehow it won't let me pass {find: @components} instead of {find: components} in the rollup.config.js

Collapse
 
ozzythegiant profile image
Oziel Perez

@sherlockcodes See my new comment above on how to do this

Collapse
 
mustofa profile image
Habib Mustofa

If you use VSCode, you also need configure it on paths in jsconfig.json.
Thanks anyway.

Collapse
 
jmsunseri profile image
Justin Sunseri

I'm trying to do this in a typescript Svelte project and it seems to work on my .svelte files but fails on my .ts files. I changed my resolve array to include ts.