将 tailwindcss 与 React 一起使用,清除后大小没有减小

Using tailwindcss with React, size not decreased after purging

我尝试使用弹出的 create-react-app 设置顺风。我成功地让它工作但未能清除大小。这是我的设置

./src/assets/styles/tailwind.css

@tailwind base;

@tailwind components;

@tailwind utilities;

postcss.config.js

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

tailwind.config.js

module.exports = {
  purge: ["./src/**/*.js"],
  theme: {
    extend: {}
  },
  variants: {},
  plugins: []
};

package.json

"scripts": {
    "start": "node scripts/start.js && postcss src/assets/styles/tailwind.css -o src/assets/styles/main.css -w",
    "build": "node scripts/build.js && postcss src/assets/styles/tailwind.css -o src/assets/styles/main.css"
}

index.js

import "./assets/styles/main.css";
// ...

我尝试创建这样的组件及其工作

<div className="w-64 h-64 bg-red-200">hai</div>

但是当我构建时,即使我在配置中给出了清除路径,大小也没有减少。无论我是否添加清除路径,它都是恒定的 143kb。我也在 postcss.config.js 尝试过这样的手动清除,但没有用

// postcss.config.js
const purgecss = require("@fullhuman/postcss-purgecss")({
  // Specify the paths to all of the template files in your project
  content: [
    "./src/**/*.js"
    // etc.
  ],

  // This is the function used to extract class names from your templates
  defaultExtractor: (content) => {
    // Capture as liberally as possible, including things like `h-(screen-1.5)`
    const broadMatches = content.match(/[^<>"'`\s]*[^<>"'`\s:]/g) || [];

    // Capture classes within other delimiters like .block(class="w-1/2") in Pug
    const innerMatches = content.match(/[^<>"'`\s.()]*[^<>"'`\s.():]/g) || [];

    return broadMatches.concat(innerMatches);
  }
});

module.exports = {
  plugins: [
    require("tailwindcss"),
    require("autoprefixer"),
    ...(process.env.NODE_ENV === "production" ? [purgecss] : [])
  ]
};

我的设置有什么问题?

使用最新版本,从 1.4.0 开始,您不需要手动配置 PurgeCSS。

// postcss.config.js
module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer')
    ]
}
//tailwind.config.js
module.exports = {
  purge: [
      './src/**/*.js'
  ],
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}
// package.json
  "scripts": {
    "start": "npm run build:css && react-scripts start",
    "build": "NODE_ENV=production npm run build:css && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "build:css": "postcss tailwind.css -o src/main.css"
  },

注意 NODE_ENV=production

documentation 说:

Now whenever you compile your CSS with NODE_ENV set to production, Tailwind will automatically purge unused styles from your CSS.

我也遇到了同样的问题。这对我有帮助:

https://tailwindcss.com/docs/optimizing-for-production#enabling-manually

我必须在我的 tailwind.config.js 文件中手动添加此代码:

// tailwind.config.js
module.exports = {
  purge: {
    enabled: true,
    content: ['./src/**/*.html'],
  },
  // ...
}

希望对您有所帮助。