如何在 svelte 组件中使用 tailwindcss @apply 指令 <style>

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

这个有效:

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

这行不通:

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

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

我查看了 Svelte 的文档,但它解释了我没有使用的 SvelteKit 的过程。我怎样才能让它发挥作用?

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

您需要为 Webpack 安装 svelte-preprocess and use it in the svelte-loader

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(),
    ...
  ]
}

(您可能需要各种对等依赖项,例如 postcss 本身和 postcss-load-config,具体取决于您使用的功能类型。)