Use tailwindcss custom config in JS/TS parts of a SvelteKit app

An handy hack to use your tailwindcss tokens in your applicative code
*

original post: https://gist.github.com/0gust1/aa8c8b831428cdd7a5535e92cbf02f04

If you use tailwind as a styling/design-system engine for your app, you may have defined custom colors, spacings or other custom “design tokens”.

Sometimes you may need to access values of this custom config in your app’s JS/TS files or Svelte files (<script> part).

This is often the case if you do some advanced front-end rendering using canvas, svg, d3 or webGL. And/Or if you want to perform calculations or interpolation on theses values.

TLDR;

  • Prerequisite: a working SvelteKit+tailwindcss project
  • In svelte.config.js, add: kit.alias.tailwindConfig: 'tailwind.config.cjs'.
  • add optimizeDeps.include:['tailwindConfig'] and server.fs.allow:[searchForWorkspaceRoot(process.cwd())] in vite.config.js

Now you can do import tailwindConfig from 'tailwindConfig'; in your JS/TS/Svelte files, and use it later like tailwindConfig.theme.colors.yourCustomColor[500].

It may be possible that this trick works in other Vite-based projects, but I haven’t tested it. If you do, please let me know.


as an example, our vite.config.ts file:

import { sveltekit } from '@sveltejs/kit/vite';
import type { UserConfig } from 'vite';
import { searchForWorkspaceRoot } from 'vite';
const config: UserConfig = {
  plugins: [sveltekit()],
  server: {
    fs: {
      allow: [searchForWorkspaceRoot(process.cwd())]
    }
  },
  optimizeDeps: {
    include: ['tailwindConfig']
  }
};

export default config;