控制文件体积

使生成的 CSS 文件保持体积小并且功能完整的方法。

使用默认配置,Tailwind CSS 的文件体积即便是经过精简和 gzip 压缩之后仍有 58.1kb 。

以下是与其它流行框架的文件体积比较:

框架 原始体积 Minified Gzip Brotli
Tailwind 477.6kb 350.4kb 58.8kb 17.1kb
Bootstrap 187.8kb 152.1kb 22.7kb 16.7kb
Bulma 205.6kb 172.4kb 23.0kb 18.0kb
Foundation 154.1kb 119.2kb 15.9kb 12.9kb
Tachyons 111.7kb 71.8kb 13.4kb 7.5kb
Semantic UI 809.4kb 613.8kb 100.6kb 77.8kb
Materialize 175.0kb 138.5kb 21.1kb 17.1kb

通过对比,Tailwind 显然处于不利的位置 (即使使用 Brotli 替代 gzip 仍然体积太大),但是你可以使用许多方法来大幅减小文件体积。


删除无用的 CSS 代码

Mozilla 的 Firefox Send 是基于 Tailwind 构建的,但是其 CSS 文件体积在经过精简(minified)之后仅有 13.1kb,gzip 压缩之后只有 4.7kb!这是怎么做到的?

他们使用的是 Purgecss,这是一个用于删除项目中没有实际使用的 CSS 代码的工。Purgecss 对于 Tailwind 特别有效,因为 Tailwind 为你自动生成了数千个工具类(utility classes),其中大部分并不会实际用到。

例如,Tailwind 为每个断点For example, Tailwind generates margin utilities for every size in your spacing scale, for every side of an element you might want to apply margin to, at every breakpoint you are using in your project. This leads to hundreds of different combinations that are all important to have available, but not all likely to be needed.

当 Purgecss 应用到 Tailwind 上时,一般生成的 CSS 文件在经过压缩之后都不会超过 10kb 。

设置 Purgecss

将来,我们可能会将 Purgecss 直接集成到 Tailwind 中,但是目前的最佳使用方法是将 Purgecss作为 PostCSS 插件使用。

要开始使用 Purgecss,首先要安装 @fullhuman/postcss-purgecss

# Using npm
npm install @fullhuman/postcss-purgecss --save-dev

# Using yarn
yarn add @fullhuman/postcss-purgecss -D

接下来,将其作为最后一个插件添加到 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/**/*.html',
    './src/**/*.vue',
    './src/**/*.jsx',
    // etc.
  ],

  // Include any special characters you're using in this regular expression
  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
})

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

注意,在上述例子中,我们只在生产环境中开启了 Purgecss。我们建议以这种方式配置 Purgecss,因为这它的运行速度可能会很慢,而在开发过程中,最好让每个类(class)都可用,这样就不用每次修改 HTML 时都要重新编译了。

Writing purgeable HTML

Purgecss uses "extractors" to determine what strings in your templates are classes. In the example above, we use a custom extractor that will find all of the classes Tailwind generates by default:

const purgecss = require('@fullhuman/postcss-purgecss')({
  // ...
  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
})

The way it works is intentionally very naive. It doesn't try to parse your HTML and look for class attributes or dynamically execute your JavaScript — it simply looks for any strings in the entire file that match this regular expression:

/[\w-:/]+(?<!:)/g

That means that it is important to avoid dynamically creating class strings in your templates with string concatenation, otherwise Purgecss won't know to preserve those classes.

Don't use string concatenation to create class names

<div :class="text-{{ error ? 'red' : 'green' }}-600"></div>

Do dynamically select a complete class name

<div :class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

As long as a class name appears in your template in its entirety, Purgecss will not remove it.

Understanding the regex

The /[\w-/:]+(?<!:)/g regular expression we recommend as a starting point matches all of the non-standard characters Tailwind uses by default, like : and /.

It also uses a negative lookbehind to make sure that if a string ends in :, the : is not considered part of the string. This is to ensure compatibility with the class object syntax supported by Vue and the Classnames library for React:

<!-- Match `hidden`, not `hidden:` -->
<div :class="{ hidden: !isOpen, ... }"><!-- ... --></div>

It's important to note that because of the negative lookbehind in this regex, it's only compatible with Node.js 9.11.2 and above. If you need to use an older version of Node.js to build your assets, you can use this regular expression instead:

- /[\w-/:]+(?<!:)/g
+ /[\w-/:]*[\w-/:]/g

Customizing the regex

If you're using any other special characters in your class names, make sure to update the regular expression to include those as well.

For example, if you have customized Tailwind to create classes like w-50%, you'll want to add % to the regular expression:

- /[\w-/:]+(?<!:)/g
+ /[\w-/:%]+(?<!:)/g

Removing unused theme values

If you can't use Purgecss for one reason or another, you can also reduce Tailwind's footprint by removing unused values from your configuration file.

The default theme provides a very generous set of colors, breakpoints, sizes, margins, etc. to make sure that when you pull Tailwind down to prototype something, create a CodePen demo, or just try out the workflow, the experience is as enjoyable and fluid as possible.

We don't want you to have to go and write new CSS because we didn't provide enough padding helpers out of the box, or because you wanted to use an orange color scheme for your demo and we only gave you blue.

This comes with a trade-off though: the default build is significantly heavier than it would be on a project with a purpose-built configuration file.

Here are a few strategies you can use to keep your generated CSS small and performant.

Limiting your color palette

The default theme includes a whopping 93 colors used for backgrounds, borders, and text, all of which also have hover: and focus variants, as well as responsive variants at the five default screen sizes.

This means that by default, there are 4185 classes generated from this color palette out of 8271 classes total in the entire default build.

Very few projects actually need this many colors, and removing colors you don't need can have a huge impact on the overall file size.

Here's how using a smaller color palette affects the final size:

Colors Original Minified Gzip Brotli
93 (default) 477.6kb 350.4kb 58.8kb 17.1kb
50 361.3kb 260.3kb 45.7kb 13.9kb
25 293.1kb 207.2kb 38.0kb 12.2kb

Removing unused breakpoints

Since almost every Tailwind utility is copied for every screen size, using fewer screen sizes can have a huge impact on the overall file size as well.

Here's how defining fewer screens affects the output:

Breakpoints Original Minified Gzip Brotli
4 (default) 477.6kb 350.4kb 58.8kb 17.1kb
3 380.9kb 279.7kb 47.4kb 16.3kb
2 284.2kb 209.0kb 36.0kb 15.0kb
1 187.5kb 138.3kb 24.5kb 13.7kb

If you only need 3 screen sizes and 35 colors, you're down to 32.5kb after gzip (11.7kb after Brotli!) without changing anything else.

Disabling unused utilities and variants

If you don't expect to need a certain utility plugin in your project at all, you can disable it completely by setting it to false in the corePlugins section of your config file:

// tailwind.config.js
module.exports = {
  // ...
  corePlugins: {
    float: false
  }
}

If you need a utility but don't need the responsive versions, set its variants to an empty array to generate 80% fewer classes:

module.exports = {
  // ...
  variants: {
    appearance: []
  }
}

These are mostly small wins compared to limiting your color palette or using fewer breakpoints, but they can still add up.