- Удаление неиспользуемых CSS стилей
- Инструмент разработчика Chrome
- Хорошо ли это?
- UnCSS
- Установка
- Saved searches
- Use saved searches to filter your results more quickly
- License
- uncss/uncss
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Удаление неиспользуемых CSS стилей
От автора: рассуждать о монолитных стилях довольно сложно, так как, обычно, CSS файлы часто раздуваются. Удаление неиспользуемых стилей CSS должно перевести ситуацию в управляемое русло. Прежде чем мы начнем искать неиспользуемые стили, стоит отметить, что существует множество других стратегий написания обслуживаемых стилей. Наши стили можно разделить на логические части (макет страницы, кнопки, сетки, виджеты и т.д.) и использовать понятную систему именования (например, БЭМ). Как правило, разработчики делают это еще до того, как ищут неиспользуемые правила. Я думаю, это правильно, ведь стили имеют долгосрочное воздействие.
Еще одна причина, по которой не так часто урезают правила – просто неудобно искать и удалять неиспользуемые стили в чем-либо, что больше маленького веб-проекта. Если контент не статичен, как понять, какие правила используются и где?
Инструмент разработчика Chrome
Оказывается, в инструментах разработчика Chrome уже есть встроенная функция. Я испытал ее на сайте, на котором, как я знал, было много стилей, которые можно удалить. Ощущения были смешанные. Порог входа очень низкий, особенно для разработчиков, которые уже работали с панелью разработчика Chrome. Устанавливать ничего не нужно, это приятно.
Что нужно сделать для проверки стилей на сайте:
Откройте интересующий сайт
Онлайн курс по JavaScript
Научитесь создавать приложения со сложными интерфейсами
Это основной язык для современной веб-разработки — почти 100% сайтов работает на JavaScript. Освойте его с нуля всего за 4 месяца, и вы сможете зарабатывать от 70 000 рублей.
Откройте панель разработчика
Перейдите на вкладку audits
Выберите опцию Web Page Performance и запустите
В части результатов будет «Remove unused CSS rules». Если этого нет, значит, у вас нет неиспользуемых стилей. Поздравляю! Результат разбит по стилям. Разбивка не просто по файлам, а по блокам style. Реально полезная функция, так как нам нужны только те стили, которые писали мы. По крайней мере, в рамках этой статьи.
Хорошо ли это?
Я не нашел супер простого способа экспортировать результат из Chrome. Можно копировать прямо из блока, но его сначала нужно развернуть. Это делает разбор результатов немного неудобным. Запуск теста в браузере еще дальше отталкивает нас от работы с кодом, что, возможно, приведет к тому, что мы будем забывать тестировать сайт.
Вывод: для начала полезно, но не долгосрочное решение.
UnCSS
Для поиска неиспользуемых стилей можно задействовать инструменты командной строки. UnCSS – интересный экземпляр. Он вытягивает страницу через phantomJS и ловит стили, вставленные через JS. Я очень хотел попробовать этот инструмент, так как он решал мою проблему, ведь панель разработчика Chrome совсем не связана с редактированием кода. С помощью UnCSS результат можно сохранить прямо в файл, идеально.
Установка
У меня не получилось выполнить npm install uncss на Ubuntu. Ничего серьезного, оказалось, я забыл пару зависимостей. Команды для установки недостающих библиотек, которые я запускал:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Remove unused styles from CSS
License
uncss/uncss
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
UnCSS is a tool that removes unused CSS from your stylesheets. It works across multiple files and supports Javascript-injected CSS.
The process by which UnCSS removes the unused rules is as follows:
- The HTML files are loaded by jsdom and JavaScript is executed.
- All the stylesheets are parsed by PostCSS.
- document.querySelector filters out selectors that are not found in the HTML files.
- The remaining rules are converted back to CSS.
Please note:
- UnCSS cannot be run on non-HTML pages, such as templates or PHP files. If you need to run UnCSS against your templates, you should probably generate example HTML pages from your templates, and run uncss on those generated files; or run a live local dev server, and point uncss at that.
- UnCSS only runs the Javascript that is run on page load. It does not (and cannot) handle Javascript that runs on user interactions like button clicks. You must use the ignore option to preserve classes that are added by Javascript on user interaction.
var uncss = require('uncss'); var files = ['my', 'array', 'of', 'HTML', 'files', 'or', 'http://urls.com'], options = banner: false, csspath: '../public/css/', htmlroot: 'public', ignore: ['#added_at_runtime', /test\-[0-9]+/], ignoreSheets: [/fonts.googleapis/], inject: function (window) window.document.querySelector('html').classList.add('no-csscalc', 'csscalc'); >, jsdom: userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)', >, media: ['(min-width: 700px) handheld and (orientation: landscape)'], raw: 'h1 < color: green >', report: false, strictSSL: true, stylesheets: ['lib/bootstrap/dist/css/bootstrap.css', 'src/public/css/main.css'], timeout: 1000, uncssrc: '.uncssrc', userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)', >; uncss(files, options, function (error, output) console.log(output); >); /* Look Ma, no options! */ uncss(files, function (error, output) console.log(output); >); /* Specifying raw HTML */ var rawHtml = '. '; uncss(rawHtml, options, function (error, output) console.log(output); >);
UnCSS can also be used in conjunction with other JavaScript build systems, such as Grunt, Broccoli or Gulp!
Usage: uncss [options] e.g. uncss https://getbootstrap.com/docs/3.3/examples/jumbotron/ > stylesheet.css Options: -h, --help output usage information -V, --version output the version number -i, --ignore Do not remove given selectors -m, --media Process additional media queries -C, --csspath Relative path where the CSS files are located -s, --stylesheets Specify additional stylesheets to process -S, --ignoreSheets Do not include specified stylesheets -r, --raw Pass in a raw string of CSS -t, --timeout Wait for JS evaluation -H, --htmlroot Absolute paths' root location -u, --uncssrc Load these options from -n, --noBanner Disable banner -a, --userAgent Use a custom user agent string -I, --inject Path to javascript file to be executed before uncss runs -o, --output Path to write resulting CSS to
Note that you can pass both local file paths (which are processed by glob) and URLs to the program.
- banner (boolean, default: true ): Whether a banner should be prepended before each file block in the processed CSS.
- csspath (string): Path where the CSS files are related to the HTML files. By default, UnCSS uses the path specified in the .
- htmlroot (string): Where the project root is. Useful for example if you have HTML that references local files with root-relative URLs, i.e. href=»/css/style.css» .
- ignore (string[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors:
/* uncss:ignore */ .selector1 < /* this rule will be ignored */ > .selector2 < /* this will NOT be ignored */ > /* uncss:ignore start */ /* all rules in here will be ignored */ /* uncss:ignore end */
'use strict'; module.exports = function (window) window.document.querySelector('html').classList.add('no-csscalc', 'csscalc'); >;
inject: function(window) window.document.querySelector('html').classList.add('no-csscalc', 'csscalc'); > >
< "ignore": [".unused", "/^#js/"], "stylesheets": ["css/override.css"] >
UnCSS can be used as a PostCSS Plugin.
postcss([require('uncss').postcssPlugin]);
See PostCSS docs for examples for your environment.
Note: Depending on your environment, you might not be able to use uncss as a PostCSS plugin since the plugin is not directly exported. In such cases, use the wrapper library postcss-uncss.
- html (string[]): provide a list of html files to parse for selectors and elements. Usage of globs is allowed.
- ignore (string[] | RegExp[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors in your CSS:
/* uncss:ignore */ .selector1 < /* this rule will be ignored */ > .selector2 < /* this will NOT be ignored */ >
html: ['index.html', 'about.html', 'team/*.html'], ignore: ['.fade'] >
Copyright (c) 2019 Giacomo Martino. See the LICENSE file for license rights and limitations (MIT).
About
Remove unused styles from CSS