翻譯:使用PurgeCSS刪除未使用的CSS

前言

爲了提升英文水平,嘗試着翻譯一些英文技術文章,首先就從這個Vue的小技巧文章開始,目前英文版一共22篇。計劃用時2~3個月翻譯完成。css

目前進度[5/22]html

原文連接

Remove unused CSS with PurgeCSSvue

譯文

咱們能夠用不一樣的方式處理Web性能,其中之一就是刪除咱們在應用程序中不使用的全部JS和CSS。git

就CSS而言,當咱們使用Bootstrap、Bulma或Tailwind等框架,以及面對大型應用程序或遺留應用程序時,這一點甚至更爲重要。github

PurgeCSS是一種在應用程序中比較字符串來刪除未使用的CSS的工具。這有一些優勢,可是也有一些問題,因此請對後面的白名單部分保持關注。框架

例如,VueDese的網站是使用Tailwind在nuxt(靜態生成)上構建的,它使用purgecss優化生成的CSS。工具

若是我禁用PurgeCSS,你會看到Tailwind css有485Kb。post

若是我激活PurgeCSS,它會降到16kb:性能

每一個項目中PurgeCSS配置會有所不一樣。它能夠設置爲Webpack插件或Postcss插件。優化

在VueDese這個案例中,我使用Postcss插件。因此,我有一個postcss.config.js文件,內容以下:

const purgecss = require("@fullhuman/postcss-purgecss");

const plugins = [...];

if (process.env.NODE_ENV === "production") {
  plugins.push(
    purgecss({
      content: [
        "./layouts/**/*.vue",
        "./components/**/*.vue",
        "./pages/**/*.vue"
      ],
      whitelist: ["html", "body"],
      whitelistPatternsChildren: [/^token/, /^pre/, /^code/],
    })
  );
}

module.exports = { plugins };
複製代碼

基本上,你只須要設置在哪裏(文件夾路徑)使用Content屬性查找匹配的類。

另外,你可能要設置白名單來標記一些類,省得被誤刪除。你至少須要在html和body以及任何動態類中這樣作。

在個人案例中,我會使用prismjs高亮代碼塊,而且添加了幾個token類,以及precode標籤中的樣式。爲了排除它們(不使用PurgeCSS刪除),我須要使用whitelistPatternsChildren屬性。

此外,Tailwind還須要一個自定義提取器(這裏參考得是Tailwind文檔上得方法),以便與purgecss一塊兒正常工做。總之,VueDese的整個postss.config.js文件包含如下內容:

const join = require("path").join;
const tailwindJS = join(__dirname, "tailwind.js");
const purgecss = require("@fullhuman/postcss-purgecss");

class TailwindExtractor {
  static extract(content) {
    return content.match(/[A-Za-z0-9-_:\/]+/g) || [];
  }
}

const plugins = [require("tailwindcss")(tailwindJS), require("autoprefixer")];

if (process.env.NODE_ENV === "production") {
  plugins.push(
    purgecss({
      content: [
        "./layouts/**/*.vue",
        "./components/**/*.vue",
        "./pages/**/*.vue"
      ],
      whitelist: ["html", "body"],
      whitelistPatternsChildren: [/^token/, /^pre/, /^code/],
      extractors: [
        {
          extractor: TailwindExtractor,
          extensions: ["html", "vue"]
        }
      ]
    })
  );
}

module.exports = {
  plugins
};
複製代碼

今天就到此爲止!

你能夠在線閱讀文章tip online(能夠 複製/粘貼 代碼),可是請你記住,若是你喜歡,要和全部同事分享VueDose

下週見。

個人理解

當你的項目足夠大的或者足夠複雜或者有很大的遺留包袱的時候,你能夠經過一些手段,去刪除代碼中無用的js和css,這樣作會大大減小你的項目體積!這篇文章介紹了使用Postcss插件採用PurgeCSS的方式去刪除css,而且使用應用了Tailwind框架案例作出了代碼說明。

關於更多的PurgeCSS請前往github

關於去除無用css還有一個好用的庫UnCSS,想要了解詳情請前往github

結尾

水平有限,不免有錯漏之處,望各位大大輕噴的同時可以指出,跪謝!

其它翻譯

一、翻譯:提升vue.js中大型數據的性能
二、翻譯:測量vue應用運行時的性能!
三、使用PurgeCSS刪除未使用的CSS
四、翻譯:Vue.js 2.6.0 中的新指令v-slot
五、翻譯:使用v-bind和v-on的自適應組件

相關文章
相關標籤/搜索