In order to avoid lengthy relative path imports like this:
import Component from "../../../../components/Component.svelte";
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
]
...
}
Now we can do:
import Component from "components/Component.svelte";
yay!
Latest comments (5)
Notes:
resolveproperty no longer exists on this plugin. If you wish to use something like "@/components" in your imports, the specific way to define this is:It seems the replacement path is based on the project's root folder
It works for me. But somehow it won't let me pass
{find: @components}instead of{find: components}in therollup.config.js@sherlockcodes See my new comment above on how to do this
If you use VSCode, you also need configure it on
pathsin jsconfig.json.Thanks anyway.
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.