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

1

6

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'],
  ],
};
Twink answered 31/5, 2022 at 6:53 Comment(0)
A
3

You need to install svelte-preprocess and use it in the svelte-loader for Webpack.

The documentation for using @import gives an example:

const sveltePreprocess = require('svelte-preprocess');
...
module.exports = {
  ...
  module: {
    rules: [
      ...
      {
        test: /\.(html|svelte)$/,
        use: {
          loader: 'svelte-loader',
          options: {
            preprocess: sveltePreprocess({
              postcss: true
            })
          }
        }
      }
      ...
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    ...
  ]
}

(You may need various peer dependencies like postcss itself and postcss-load-config depending on which kinds of features you use.)

Aleida answered 31/5, 2022 at 11:48 Comment(4)
Thank you, it's working now but it won't purge unused css. I'm getting 74 warnings of unused CSS selectors as soon as I add the three @tailwind directives in my <style> tag. I tried manually setting process.env.NODE_ENV to "production" and my tailwind.config.js is bare bones.Twink
You might want to place the @tailwind directives in a global style tag on a root component (example). That should get rid of the warnings, but I do not know if the purging will automatically work.Aleida
I tried that before, but for some reason the @tailwind directives are not being treated as global. If I try to use @apply in another component I get an error "no matching @tailwind components directive". A regular CSS selector works, it affects other components. The styles are in <style global lang="postcss">Twink
Testing things further, if I only include the @tailwind directives in my main component, the tailwind classes that you apply inline to elements work fine, only when I try to use @layer components I get the error. And when I add the directives to that component as well, it complains about css duplication.Twink

© 2022 - 2024 — McMap. All rights reserved.