UNPKG

2.8 kBJavaScriptView Raw
1'use strict';
2
3var path = require('path');
4var autoprefixer = require('autoprefixer');
5var diff = require('diff');
6var chalk = require('chalk');
7
8module.exports = function(grunt) {
9
10 var options;
11 var prefixer;
12
13 /**
14 * Returns an input source map if a map path was specified
15 * or options.map value otherwise
16 * @param {string} from
17 * @returns {string|undefined}
18 */
19 function getPrevMap(from) {
20 if (typeof options.map.prev === 'string') {
21 var mapPath = options.map.prev + path.basename(from) + '.map';
22
23 if (grunt.file.exists(mapPath)) {
24 return grunt.file.read(mapPath);
25 }
26 }
27 }
28
29 /**
30 * @param {string} input Input CSS
31 * @param {string} from Input path
32 * @param {string} to Output path
33 * @returns {{css: string, map?: string}}
34 */
35 function prefix(input, from, to) {
36 var output = prefixer.process(input, {
37 map: (typeof options.map === 'boolean') ? options.map : {
38 prev: getPrevMap(from),
39 inline: options.map.inline,
40 annotation: options.map.annotation,
41 sourcesContent: options.map.sourcesContent
42 },
43 from: from,
44 to: to
45 });
46
47 return output;
48 }
49
50 grunt.registerMultiTask('autoprefixer', 'Prefix CSS files.', function() {
51 options = this.options({
52 cascade: true,
53 diff: false,
54 map: false
55 });
56
57 prefixer = autoprefixer(options.browsers, {cascade: options.cascade});
58
59 this.files.forEach(function(f) {
60 if (!f.src.length) {
61 return grunt.fail.warn('No source files were found.');
62 }
63
64 f.src
65 .forEach(function(filepath) {
66 var dest = f.dest || filepath;
67 var input = grunt.file.read(filepath);
68 var output = prefix(input, filepath, dest);
69
70 grunt.file.write(dest, output.css);
71 grunt.log.writeln('File ' + chalk.cyan(dest) + ' created.');
72
73 if (output.map) {
74 grunt.file.write(dest + '.map', JSON.stringify(output.map.toJSON()));
75 grunt.log.writeln('File ' + chalk.cyan(dest + '.map') + ' created (source map).');
76 }
77
78 if (options.diff) {
79 var diffPath = (typeof options.diff === 'string') ? options.diff : dest + '.patch';
80
81 grunt.file.write(diffPath, diff.createPatch(dest, input, output.css));
82 grunt.log.writeln('File ' + chalk.cyan(diffPath) + ' created (diff).');
83 }
84 });
85 });
86 });
87};