'SvelteKit: How to refer to the /routes folder from components and endpoints via alias, like $routes?
The next is my (simplified) project structure:
appname
|
|__src
| |__lib
| |__routes
|
|__jsconfig.json
In the jsconfig.js file, I have paths key with an alias to a './src/lib' folder in form of $lib.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"$lib": ["src/lib"],
"$lib/*": ["src/lib/*"],
}
},
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}
I want to access routes folder with $routes alias in the same way as $lib.
But if I add "$routes": ["src/routes"] in above JSON file, sveltekit cannot resolve the path starting with '$routes/somefile'
Example:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"$lib": ["src/lib"],
"$lib/*": ["src/lib/*"],
"$routes": ["src/routes"],
"$routes/*": ["src/routes/*"],
}
},
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}
endpoint.js
import { db } from '$routes/db';
What am I doing wrong?
Solution 1:[1]
You also have to tell the bundler to use it in svelte.config.js
kit: {
vite: {
resolve: {
alias: {
$routes: path.resolve('./src/routes')
}
}
}
}
That said, remember that all files in the routes folder except for the ones starting with an _ underscore) are considered to be routes. So if you have file /src/routes/db.js a user can go to http://yoursite.domain/db.
There is very rarely any reason to import a file from there and if you need to do so, it likely is not a route or endpoint and can be safely put in lib instead
Solution 2:[2]
To complement on Stephane Vanraes answer.
I'm using SvelteKit with TypeScript so I add the path to tsconfig.json as follows:
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"$routes": ["src/routes"],
"$routes/*": ["src/routes/*"]
}
}
}
Then I setup svelte.config.js as follows:
import path from 'path';
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
vite:{
resolve: {
alias: {
$routes: path.resolve('./src/routes'),
}
}
},
},
};
If you are also using Vitest, you can setup export the object
provided under config.kit.vite and import it in your vite.config.ts
file as follows:
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { viteConfig } from './svelte.config.js';
import type { UserConfig } from 'vite';
export default defineConfig({
...(viteConfig as UserConfig),
plugins: [svelte()],
});
This way you can import routes for testing from your Vitest suites.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephane Vanraes |
| Solution 2 | Esteban Borai |
