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

Time:06-01

This works:

<div  />

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'],
  ],
};

CodePudding user response:

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.)

  • Related