Skip to content

Instantly share code, notes, and snippets.

@0gust1
Last active July 21, 2023 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0gust1/aa8c8b831428cdd7a5535e92cbf02f04 to your computer and use it in GitHub Desktop.
Save 0gust1/aa8c8b831428cdd7a5535e92cbf02f04 to your computer and use it in GitHub Desktop.
SvelteKit: how to import tailwindcss custom config to be used in JS/TS parts

How to import tailwindcss custom config in JS/TS parts of a SvelteKit app

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 file in JS/TS files or in Svelte files (<script> part).

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

TLDR;

  • Prerequisite: a working SvelteKit+tailwindcss project
  • In 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] for example.


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;
@drewbitt
Copy link

If you do this approach and have a plugin in tailwind.config.cjs, this will not work

const config = {
...
plugins: [require('@tailwindcss/typography'), require('daisyui')],
...
};

module.exports = config;

Error:

ReferenceError: require is not defined
    at /tailwind.config.cjs:106:11

@Wheeskeey
Copy link

If you do this approach and have a plugin in tailwind.config.cjs, this will not work

const config = {
...
plugins: [require('@tailwindcss/typography'), require('daisyui')],
...
};

module.exports = config;

Error:

ReferenceError: require is not defined
    at /tailwind.config.cjs:106:11

Did you solve it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment