📜 ⬆️ ⬇️

10 PostCSS plugins that will save time for your coder


We, front-line vendors, have such a category of tools that do not solve the tasks before us, but rather influence the process of their solution. Change it. Attitudes towards such tools are very different - starting from a mania in the spirit of “let's shove this thing everywhere, it's so cool” and ending with excuses like “if it doesn’t solve business problems, then we don’t need it”. But, anyway, today we will talk about PostCSS - one of these tools.


The HYIP wave has long passed, and very little has been said about PostCSS lately. Many newbies do not even know what it is. I think it's time to look at this tool from the point of view of practical use in the most ordinary projects, where people solve problems rather than play with modern technologies.


PostCSS vs SASS


Oh ... Apparently I should say a few words about it. I think now a rare typesetter has not met with preprocessors. SASS or my favorite LESS, less commonly Stylus, is used on large projects and on small ones. Someone is trying to squeeze the maximum out of them, someone is using a minimalist set - nesting, variables, imports. But, anyway, these tools help with syntax questions. They make it easier for us to write code.


About two or three years ago, PostCSS was constantly compared to preprocessors. And this is understandable. Formally, it can be used to do everything the same, to make some syntax that will be more convenient than pure CSS. But all this caused turbulences among the masses, mainly because everyone made something different with the help of PostCSS. Countless unknown plugins, millions of combinations and no one except the author of this or that config understood how it works and what it does. It's like Vim or Emacs - you can make a spaceship out of them, but teaching another developer to use them will be very difficult.


But if these comparisons are discarded, then PostCSS is a tool that allows you to take our CSS and do something with it. No one bothers to use SASS for the sake of syntax, and after assembly, insert PostCSS and do something with the result. They do not contradict each other.


Old does not mean idle


Recently, we have fashionable to create combines that can do everything that only comes to mind, and their development never stops. And if there are no fresh commits in the repository for a couple of months, then everything - we can assume that it is outdated and use it now - not comme il faut. I exaggerate, of course, but I think you yourself noticed how absurd it sometimes comes.


In the PostCSS world, usually one plugin solves one problem. You can see elements of the Unix philosophy here. From this a logical conclusion follows - if the plugin is already solving its problem, then nothing more needs to be done with it anymore. You may come across plug-ins that have not been updated for years, but this does not mean that they suddenly stopped solving the tasks for which they were created.


But let's get started ... I collected a dozen plug-ins, which in practice showed their ability to simplify the life of layout designers and save time during development. But you can always add something in the comments.


â„–1. Doiuse


https://github.com/anandthakker/doiuse


I think we all faced such a problem: you write code, check it in chrome - everything is ok. Check in FF - approx. And then in the mobile Safari everything falls apart. Or in the edge. And you sit and do not understand what is wrong. Then you stare at the code for a long time, drink tea, and suddenly there comes an insight that some property is not supported in some kind of browser. You go to caniuse and see the confirmation of the obvious.



Of course, with experience hands themselves remember which properties to avoid, but anything can happen. You can not sleep, there may be short deadlines and nerves, the list of browsers that need to be supported may change. And then the experience will begin to fail. Doiuse is a tool that helps a lot in such situations.


The principle of operation is simple - we feed him a list of browsers and our CSS. The plugin goes to the caniuse database and in real time gives us the answer that we were looking for from what is not supported.


We can set the list of browsers directly in package.json. Simple and convenient. PostCSS uses browserslist and, if you haven't seen it before, it looks like this:


"browserslist": [ "> .5% and last 2 versions", "not dead", "not OperaMini all", "ie >= 11", "Edge >= 12" ] 

There is also a doiuse config in which you can make it ignore certain property groups, if you are sure that this does not affect anything. For example, if you use polifila or nothing will change from the loss of support for some property:


 ignore: [ 'will-change', 'object-fit' ] 

The standard log that the plugin gives is not very readable. It contains a lot of information and it is not very convenient to perceive it. But this is a fixable matter. In the same config we can do our function to form a log.


Use console.log to figure out how the object is structured, which passes PostCSS to this function. There are many interesting things.

My practice has shown that the most convenient option is to display selectors and specific properties that are not supported without specifying browsers and lines of code. If BEM or some analogs are used in the project, and the code of the components is distributed among individual files, then this approach allows you to quickly find the problem area without loading the brain.


 onFeatureUsage(info) { const selector = info.usage.parent.selector; const property = `${info.usage.prop}: ${info.usage.value}`; let status = info.featureData.caniuseData.status.toUpperCase(); if (info.featureData.missing) { status = 'NOT SUPPORTED'.red; } else if (info.featureData.partial) { status = 'PARTIAL SUPPORT'.yellow; } console.log(`\n${status}:\n\n ${selector} {\n ${property};\n }\n`); } 

In order not to write special character sequences for colors in the console, you can connect the colors package, it will be more convenient with it.


When building, there will be approximately the following output in the console:


 NOT SUPPORTED: html { -ms-text-size-adjust: 100%; } NOT SUPPORTED: html { -webkit-text-size-adjust: 100%; } PARTIAL SUPPORT: body { display: flex; } 

â„–2. Autoprefixer


https://github.com/postcss/autoprefixer


It is even embarrassing to talk about him, but too often I see people who in 2019 write prefixes with their hands and still assure those around them that they know exactly which ones are needed and which ones are not. Such actions lead to the fact that the code is overgrown with a bunch of unnecessary prefixes and becomes completely unreadable. This affects productivity. On the other hand, if you need the support of dinosaurs, then you can always forget something. So it’s worth getting rid of manual labor.


The autoprefixer works all with the same caniuse base, uses the same browserslist and can add to CSS those prefixes that are really needed in the browsers we specified. In this case, the code itself becomes cleaner, and the work goes faster.


Number 3. Stylelint


https://github.com/stylelint/stylelint


When you print a lot and quickly, then sooner or later you start to make many mistakes without noticing them. The eye is washed out. In the case of CSS, this can give a funny (actually not) effect; when you look at the browser, you see a problem with layout. You look at the code - it's not there. You look in the browser - it is. And in the code - no. As a result, you can search for a difficult problem for a long time, completely unaware that you just messed up. That such was not, invented linter.


Stylelint is a popular option. He knows how to work with the syntaxes of the main preprocessors, knows about the latest trends in CSS, can be customized to your taste - configs are similar to those of eslint. Formally, this tool can be used by itself, without PostCSS, but not to mention it here would be wrong.


â„–4. Postcss-flexbugs-fixes


https://github.com/luisrudge/postcss-flexbugs-fixes


Or in a broader sense, postcss-fixes , which includes this plugin. Slowly but surely, the flexes supplant the old approach to layout on floats. This is good, but we all know that a set of bugs is associated with them. These are described in the flexbugs repository. Some of them require special attention, but there are also a few that are so simple that they constantly fly out of my head. For example, IE ignores the calc function in the shorthand property flex. This is not so often necessary, but if necessary, the hands themselves can write an abridged version and then they have to think a long time what the problem is. Fortunately, this case can be fixed automatically. The postcss-flexbugs-fixes plugin comes to the rescue.


In the calc example, he finds fragments like this in the code:


 .foo { flex: 1 0 calc(1vw – 1px); } 

And expand them:


 .foo { flex-grow: 1; flex-shrink: 0; flex-basis: calc(1vw - 1px); } 

Simple and convenient.


â„–5. Postcss-preset-env


https://github.com/csstools/postcss-preset-env


Since we are talking about browser support, it will not be superfluous to say about postcss-preset-env. Previously, cssnext performed the same role. This plugin will be useful if you are interested in new trends in CSS.



Many of the innovations are technically possible to implement with the old methods, it will just be long, verbose and ugly. Preset-env helps to write code in a new way, save time on it, and then convert it into the old reliable version. Of course, some things like custom properties are not implemented at all in older browsers, so folbekbacks will be used there.


As you can guess from the name of the tool, it resembles the same preset Babel. There is still a lot of converters assembled in one stable set. Some transformations require the subsequent connection of polyfile scripts on the client, but most are implemented purely by CSS. As far as I understand, for Stage2 + scripts are not needed. In any case, did not encounter their necessity. Correct me if I missed something there.


â„–6. Postcss-animation


https://github.com/zhouwenbin/postcss-animation


I often hear from different people (mostly backenders who are not very strong in CSS) that they want to use separate animations from animate.css , but they consider it a bad idea to include the entire library. It is quite logical. But as a result, they spend a lot of time trying to repeat these animations on their own.



The postcss-animation plugin speeds up this process a lot. We write only the name of the animation, for example:


 .foo { animation-name: bounce; } 

And he pulls up the implementation from animate.css and inserts it into the code.


 .foo { animation-name: bounce; } @keyframes bounce { from, 20%, 53%, 80%, to { animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000); transform: translate3d(0,0,0); } 40%, 43% { animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060); transform: translate3d(0, -30px, 0); } 70% { animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060); transform: translate3d(0, -15px, 0); } 90% { transform: translate3d(0,-4px,0); } } 

â„–7. List-selectors


https://github.com/davidtheclark/list-selectors


When you have several designers and a lot of styles, the question arises about code review, that it would be nice sometimes to see the big picture with all the selectors that we have. To know which IDs are used, whether there are tag selectors, or to what extent the adopted methodology is respected. This is especially important when you check the beginner code, which can write strange things that will formally work, but will actually go against accepted agreements (these agreements are not well documented everywhere and it is possible to automate such things). Most scroll through numerous files with styles to check the adequacy of selectors for a long time. We need a way to isolate them and show them separately. List-selectors just solves this problem.


In the same way as doiuse, this plugin allows you to use your function to prepare information for display on the screen. You can display only what interests you, or paint everything in different colors. As an example:


 require('list-selectors').plugin((list) => { const inspect = require('util').inspect; console.log('SELECTORS:'.blue); console.log(inspect(list.selectors, { maxArrayLength: null }).blue); console.log('IDS:'.red); console.log(inspect(list.simpleSelectors.ids, { maxArrayLength: null }).red); }) 

This example will have a long, long list of selectors:


 SELECTORS: [ '.mui-progress-bar', '.mui-progress-bar > .indicator', '.mui-progress-bar > .value', '.mui-progress-bar.-radial', '.mui-progress-bar.-radial > .indicator', '.mui-progress-bar.-radial > .indicator > .background', '.mui-progress-bar.-radial > .indicator > .progress', '.mui-progress-bar.-radial > .value', . . . 

â„–8. Immutable-css


https://github.com/johno/immutable-css


Another thing to watch out for is interrupting styles from third-party libraries. If we hooked up some kind of library, and then we begin to write our styles for selectors from it, then in the end we get tangled code in which we cannot make out where it came from. This can lead to random bugs, which then take too much time out of the blue. The more times we redefine something, the more difficult it is to finally understand what is happening, although the problem itself, which needs to be solved, can be very simple. In this situation, a tool called immutable-css may come in handy.


In general, the principle of its operation is simple: it takes files with styles, if it finds matches by selectors - it begins to resent:


 ! .button was mutated 2 times [line 93, col 1]: /css/basscss.css [line 3, col 1]: /css/custom.css [immutable-css] ! .left was mutated 2 times [line 291, col 1]: /css/basscss.css [line 4, col 1]: /css/custom.css [immutable-css] 

The only problem with this tool is that it does not support non-CSS syntax. So if in the project preprocessors are used, then it is necessary to compare already collected files. But in general, if the task is to just make sure that no one accidentally rewrote styles from a third-party library, then this is not so important.


â„–9. Bye-bye!


https://github.com/AoDev/css-byebye


I think everyone is familiar with the situation when we gradually add some components to a working site. Some of them are sent immediately to production, and some sit for a long time and wait for their turn (for example, we cast up, but we didn’t finish the backend). Something could be an experiment or a temporary solution for the holidays. There may be many situations, but they are united by the fact that we have a lot of components, and only a small part of them are used on the combat site. It would be good to remove everything that is not used from the current build. This can significantly reduce its size, as well as reduce the headache in the future, when you need to do a redesign, for example, and the question arises, what of all this really need to be rewritten now, and what is not.



There are different approaches to this issue. Uncss comes to mind immediately. This tool automatically determines which styles are used on the pages and removes unnecessary. But in practice, this almost always leads to the fact that no one knows what is actually used and what is not. And I’ve been wondering all the time if this tool hasn’t removed anything unnecessary. But this is probably my paranoia. Although...


Bye-bye is a simpler tool that we ourselves feed a list of selectors that need to be removed from CSS. And you can use regular expressions. If you apply BEM or something else in this spirit, then with one simple regular schedule you can remove a block with everything that applies to it. Bye-bye!


This approach was quite convenient. It is immediately clear which styles are not yet used or were removed as unnecessary, while all the sources are in place, all the settings in one file, nothing is lost, it does not cause difficulties to make several different assemblies, and most importantly - the solution is simple and predictable.


â„–10. Postcss trolling


https://github.com/juanfran/postcss-trolling


All previous tools may slightly increase the productivity of your web designers, but this one just gives phenomenal results. Highly recommend.


Conclusion


PostCSS is a good help for the maker. If they are not abused, of course. For many time-consuming problems, there are ready-made solutions in the form of plug-ins, and although they often do not develop and seem to be abandoned, this does not prevent them from being used.


')

Source: https://habr.com/ru/post/457340/


All Articles