Absolute Paths in Svelte

sjafferi

Sibtain Jafferi

Posted on February 11, 2020

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!

💖 💪 🙅 🚩
sjafferi
Sibtain Jafferi

Posted on February 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Absolute Paths in Svelte
svelte Absolute Paths in Svelte

February 11, 2020