sveltesveltekit

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

  • 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

    Update 31.01.2023

    The above answer was written before a major overhaul of how routes work in SvelteKit. Nowadays routing is directory based and only the file +page.svelte will actually create a route (so /src/routes/about/+page.svelte will give you the /about route). This means that you can safely add other files and components to the route folder.