简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM