javascriptwebpacktailwind-csssveltepostcss

How do I use tailwindcss @apply directive inside a svelte component <style>


This works:

<div class="list p-2" />

This doesn't work:

<style lang="postcss">
  @tailwind base;
  @tailwind components;
  @tailwind utilities;

  @layer components {
    .list {
      @apply p-2;
    }
  }
</style>

I looked in Svelte's docs, but it explains the process with SvelteKit, which I'm not using. How can I make it work?

webpack.config.js:

...
module: {
rules: [
  {
    test: /\.css$/i,
    use: ['style-loader', 'css-loader', 'postcss-loader'],
  },

tailwind.config.js:

module.exports = {
  purge: [
    './*.html',
    './src/**/*.js',
    './src/**/*.svelte'
  ],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

postcss.config.js:

module.exports = {
  plugins: [
    ['tailwindcss'],
    ['autoprefixer'],
  ],
};

Solution

  • In case someone needs this...

    <style lang="postcss">
        .list {
          @apply p-2;
        }
    </style>
    

    EDIT: 03/26/2025

    For Tailwind 4 you have to do this:

    <style lang="postcss">
        @import "tailwindcss";
        
        .list {
          @apply p-2;
        }
    </style>