Custom lib-folder in SvelteKit

How to create a path alias in SvelteKit

Defining path aliases

If you want to rename the “lib”-folder that’s defined by SvelteKit by default or add any other directory for short imports, you have to update two configs.

  • tsconfig, so that Typescript can resolve your import alias
  • your svelte-config, which also has to know the path aliases

With these changes, every directory in “src” can be resolved via path aliases, which means you get short and simple imports.

Updating the tsconfig-file

In this example, I’ll add a new directory for short imports, but the same changes apply if you want to replace “lib”.

The following code shows an updated tsconfig.json, where the “paths”-object has been enhanced with my new directory “msw”, which is an abbreviation for “mock service worker”. This folder contains all my MSW related code.

{
  "compilerOptions": {
    ...
    "paths": {
      "$lib": ["src/lib"],
      "$lib/*": ["src/lib/*"],
      "$msw": ["src/msw"],
      "$msw/*": ["src/msw/*"]
    }
  },
  ...
}

Updating the svelte-config

Now what’s left is to also update the config that’s consumed by SvelteKit, named "svelte.config.js". We simply have to update the “vite”-object configuration. Note that we have to also provide the “lib”-folder explicitly, as our customization overrides the default one, which means the “lib”-folder wouldn’t be an alias any more.

import adapter from "@sveltejs/adapter-auto";
import preprocess from "svelte-preprocess";
import path from "path";

/** @type {import('@sveltejs/kit').Config} */
const config = {
  // Consult https://github.com/sveltejs/svelte-preprocess
  // for more information about preprocessors
  preprocess: preprocess(),

  kit: {
    adapter: adapter(),
    vite: {
      resolve: {
        alias: {
          $msw: path.resolve("./src/msw"),
          $lib: path.resolve("./src/lib")
        }
      }
    }
  }
};

export default config;

Conclusion

And that’s it! With these small changes, you can use any folder in “src” with path aliases for clean and simple imports.

Suggestions

Related

Addendum

Languages