forked from dlmanning/gulp-sass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
299 lines (253 loc) · 7.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
'use strict';
/**
* Gulp plugin for sass.
* Extended version of {@link [gulp-sass](https://github.com/dlmanning/gulp-sass)}.
* @module gulp-sass-extended
*/
var gutil = require('gulp-util');
var through = require('through2');
var clonedeep = require('lodash.clonedeep');
var path = require('path');
var applySourceMap = require('vinyl-sourcemaps-apply');
/**
* The name of plugin
* @private
* @const {string}
*/
var PLUGIN_NAME = 'gulp-sass-extended';
/**
* Main plugin function
* @method
* @param {Object} options - plugin options
* @param {boolean} [sync] - use node-sass `renderSync` method
* @returns {DestroyableTransform} through2.obj
*/
var gulpSass = function gulpSass(options, sync) {
return through.obj(function (file, enc, cb) {
// create variables for work
var opts; // re-tuned options
var filePush; // fn for pushing transformed files back to stream
var errorM; // error method
var callback; // callback for node-sass `render` method
var result; // result of node-sass
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
}
if (path.basename(file.path).indexOf('_') === 0) {
return cb();
}
if (!file.contents.length) {
file.path = gutil.replaceExtension(file.path, '.css');
return cb(null, file);
}
opts = clonedeep(options || {});
opts.data = file.contents.toString();
// *** EXTENDING ***
// The ability to add custom variables from gulp task
if (opts.addVariables) {
var vars = JSON.parse( JSON.stringify(opts.addVariables) );
var varsList = [];
var generated = '/* generated */ %s';
var _isarray = require('lodash/isarray');
// format vars
for (let key in vars) {
let value = vars[key];
let variable = false;
switch (typeof value) {
case 'object':
if (null === value) {
break;
}
let list = [];
// if array - create SASS list
if (_isarray(value)) {
for (let i = 0; i < value.length; i++) {
let val = value[i];
if (typeof val == 'object') {
continue;
}
list.push(val);
}
// else - SASS map
} else {
for (let prop in value) {
let val = value[prop];
if (typeof val == 'object') {
continue;
}
list.push(prop + ': ' + val);
}
}
if (list.length) {
variable = '$' + key + ': (' + list.join(', ') + ');';
}
break;
default:
// example -> $var: 2rem;
variable = '$' + key + ': ' + value + ';';
}
if (variable) {
varsList.push(generated.replace(/%s/, variable));
}
}
// if vars parsed and exist
if (varsList.length) {
var fileContent = opts.data;
var charsetRegexp = /\@charset(.+;)/i;
varsList = varsList.join('\n');
// if has charset
if (charsetRegexp.test(fileContent)) {
fileContent = fileContent.replace(charsetRegexp, (str, group) => {
return '@charset' + group + '\n' + varsList + '\n';
});
} else {
fileContent = varsList + '\n' + fileContent;
}
// new content
opts.data = fileContent;
}
}
// we set the file path here so that libsass can correctly resolve import paths
opts.file = file.path;
// Ensure `indentedSyntax` is true if a `.sass` file
if (path.extname(file.path) === '.sass') {
opts.indentedSyntax = true;
}
// Ensure file's parent directory in the include path
if (opts.includePaths) {
if (typeof opts.includePaths === 'string') {
opts.includePaths = [opts.includePaths];
}
}
else {
opts.includePaths = [];
}
opts.includePaths.unshift(path.dirname(file.path));
// Generate Source Maps if plugin source-map present
if (file.sourceMap) {
opts.sourceMap = file.path;
opts.omitSourceMapUrl = true;
opts.sourceMapContents = true;
}
// Handles returning the file to the stream
// ============
filePush = function filePush(sassObj) {
var sassMap;
var sassMapFile;
var sassFileSrc;
var sassFileSrcPath;
var sourceFileIndex;
// *** EXTENDING ***
// The ability to get data with the results
// of a node-sass render
// in the gulp task for each file
if (typeof opts.afterRender === 'function') {
opts.afterRender(sassObj, file);
}
// Build Source Maps!
if (sassObj.map) {
// Transform map into JSON
sassMap = JSON.parse(sassObj.map.toString());
// Grab the stdout and transform it into stdin
sassMapFile = sassMap.file.replace(/^stdout$/, 'stdin');
// Grab the base file name that's being worked on
sassFileSrc = file.relative;
// Grab the path portion of the file that's being worked on
sassFileSrcPath = path.dirname(sassFileSrc);
if (sassFileSrcPath) {
//Prepend the path to all files in the sources array except the file that's being worked on
sourceFileIndex = sassMap.sources.indexOf(sassMapFile);
sassMap.sources = sassMap.sources.map(function (source, index) {
return (index === sourceFileIndex) ? source : path.join(sassFileSrcPath, source);
});
}
// Remove 'stdin' from souces and replace with filenames!
sassMap.sources = sassMap.sources.filter(function (src) {
if (src !== 'stdin') {
return src;
}
});
// Replace the map file with the original file name (but new extension)
sassMap.file = gutil.replaceExtension(sassFileSrc, '.css');
// Apply the map
applySourceMap(file, sassMap);
}
file.contents = sassObj.css;
file.path = gutil.replaceExtension(file.path, '.css');
cb(null, file);
};
// Handles error message
// ============
// *** EXTENDING ***
// The ability to set your own error handler
// from the gulp task parameters
if (typeof opts.errorHandler == 'function') {
errorM = opts.errorHandler;
delete opts.errorHandler; // delete to avoid possible conflicts
} else {
// original handler - by default
errorM = function errorM(error, throughCallback) {
var relativePath = '';
var filePath = error.file === 'stdin' ? file.path : error.file;
var message = '';
filePath = filePath ? filePath : file.path;
relativePath = path.relative(process.cwd(), filePath);
message += gutil.colors.underline(relativePath) + '\n';
message += error.formatted;
error.messageFormatted = message;
error.messageOriginal = error.message;
error.message = gutil.colors.stripColor(message);
error.relativePath = relativePath;
return throughCallback(new gutil.PluginError(
PLUGIN_NAME, error
));
};
}
if (sync !== true) {
// Async Sass render
// ============
callback = function (error, obj) {
if (error) {
error.renderFile = file.path;
return errorM(error, cb);
}
filePush(obj);
};
gulpSass.compiler.render(opts, callback);
}
else {
// Sync Sass render
// ============
try {
result = gulpSass.compiler.renderSync(opts);
filePush(result);
}
catch (error) {
error.renderFile = file.path;
return errorM(error, cb);
}
}
});
};
// Sync Sass render
// ============
gulpSass.sync = function sync(options) {
return gulpSass(options, true);
};
// Log errors nicely
// ============
gulpSass.logError = function logError(error) {
var message = new gutil.PluginError('sass', error.messageFormatted).toString();
process.stderr.write(message + '\n');
this.emit('end');
};
// Store compiler in a prop
// ============
gulpSass.compiler = require('node-sass');
// add this name
// ============
gulpSass.pluginName = PLUGIN_NAME;
module.exports = gulpSass;