Create a PostCSS Plugin to Remove Vendor Prefixes

John Otander
InstructorJohn Otander
Share this video with your friends

Social Share Links

Send Tweet

PostCSS is a CSS processor that allows you to modify source CSS with plugins. In this lesson we'll modify the CSS AST by creating a plugin that removes declarations when they contain vendor prefixes.

Instructor: [00:00] In order to write a postCSS plugin, we'll need to initialize a project, then we'll need to install the development dependencies. We install postCSS so we can run our plug in, and Jest so we can run our test.

[00:12] When the installation is complete, we can add a test script to our package JSON. We can begin our test file.

[00:19] First, we'll instantiate our Fixture CSS, then we can require postCSS, and begin scaffolding out our test.

[00:28] You can run postcss and pass it our FIXTURE. Then we can create our assertion. We'll also want to instantiate our expected CSS output. This will be the same as our FIXTURE but without any vendor prefix declarations.

[00:45] Now we can run our test. As we can see it fails, because we haven't created our plugin yet. Let's go ahead and do that.

[00:52] First, we will require a PostCSS, and then call its plugin method. Give it our plugin's name and then our function.

[01:01] Function itself will turn a function that receives the tree. With our tree, we will walk all CSS declarations. For now, we can go ahead and log them. Then in our tests, make sure we use our plugin.

[01:15] We will require the plugin and then pass it as part of an array to PostCSS. Now, run our test. As we can see, we have our declarations. Here's a prop and its value, another property, its value.

[01:34] Now, in this plugin, we will remove all vendor prefixes. We can install a library to check for us. We will yarn add is-vendor-prefixed.

[01:43] We can require is-vendor-prefixed. Then we can check to see the declaration's property is vendor-prefixed.

[01:52] When it is, we can remove the declaration. Now, we can run our test.

[02:01] As we can see, some of the properties have been removed, but we also need to check the declaration's value. Here, we can copy over our initial prop check and swap out declaration.prop for the CSS declaration's value.

[02:16] With that complete, we can run our test again. It should pass.

[02:21] Altogether, we have required PostCSS, called the PostCSS plugin, walked all declarations in our route AST structure for the CSS document, and then required is-vendor-prefixed and checked both the declaration property and the declaration value to see if either were vendor prefixed. If they were, we call declaration.remove.

[02:45] In our test, we require postCSS and the plugin, and then call postCSS or we pass it the plugin and our FIXTURE, to make sure that we get the expected outcome.