AutoPrefix Browser Vendors to your CSS style sheet with a Gulp Workflow

You can automatically add browser vendor prefixes to your CSS style sheet using a Gulp workflow and an AutoPrefixer package, this can be a huge time save and safety net to use newer CSS properties like flexbox that require cross browser prefixes.

Create a package.json file

Either run npm init in your project directory or just copy and paste the standard format to create a package.json file which is needed to manage the Gulp packages…

{
 "name": "my-project",
 "version": "1.0.0",
 "description": "description",
 "repository": {
 "type": "git",
 "url": "?.git"
 },
 "author": "Your Name",
 }

Install the required packages

npm install --save-dev gulp

npm install --save-dev gulp-autoprefixer

So installing gulp and autoprefixer – this will then automatically  adjust our package.json file

{
 "name": "my-project",
 "version": "1.0.0",
 "description": "description",
 "repository": {
 "type": "git",
 "url": "?.git"
 },
 "author": "Your Name",
 "devDependencies": {
 "gulp": "^3.9.1",
 "gulp-autoprefixer": "^3.1.1"
 }
 }

Set Up a gulpfile.js

Now we need to create the Gulp commands/tasks to set the autoprefixer into action, this is done with the gulpfile.js file,  this file also needs to be filed in your project directory.

var gulp = require('gulp'); // Load in Gulp
var autoprefixer = require('gulp-autoprefixer'); // Load in Autoprefixer
// Create the 'prefix' task
gulp.task('prefix', function () { // Naming the task 'prefix'
return gulp.src('style.css') // Set the source file
.pipe(autoprefixer({
browsers: ['last 3 versions'], // Set the Browser versions
cascade: false
}))
.pipe(gulp.dest('./')); // Set the destination file
});
// More info on options - https://github.com/postcss/autoprefixer#options and https://github.com/ai/browserslist#queries
// To tun the task in the terminal from your project directory use - gulp prefix
view raw autoprefix.js hosted with ❤ by GitHub

The above gist is documented to explain what is going on, to run the task, make sure you are in your project directory and use the command gulp prefix or whatever task you named it…

gulp prefix

For simplicity I have set the source and destination to be the same file, adjust this to your workflow, check the option links to see how else you can specify what browser versions can be used to suit your target audience.

That’s it, now all the correct vendor prefixes are in use in the style sheet.

Leave a Comment





%d bloggers like this: