|
| 1 | +const path = require('path'); |
| 2 | +const through2 = require('through2'); |
| 3 | +const gutil = require('gulp-util'); |
| 4 | +const bufferstreams = require('bufferstreams'); |
| 5 | + |
| 6 | +const pluginName = 'gulp-typed-css-modules'; |
| 7 | + |
| 8 | +module.exports = options=>{ |
| 9 | + options = options || {}; |
| 10 | + |
| 11 | + const DtsCreator = options.ctm || require('typed-css-modules'); |
| 12 | + |
| 13 | + const creator = new DtsCreator(options); |
| 14 | + |
| 15 | + return through2.obj((file, encoding, callback)=>{ |
| 16 | + const filepath = file.path; |
| 17 | + const newpath = gutil.replaceExtension(filepath, '.d.ts'); |
| 18 | + |
| 19 | + file.path = newpath; |
| 20 | + if (file.isNull()){ |
| 21 | + callback(null); |
| 22 | + return; |
| 23 | + } |
| 24 | + if (file.isBuffer()){ |
| 25 | + runtcm(filepath, creator, file.contents.toString(encoding), options) |
| 26 | + .then(content=>{ |
| 27 | + file.contents = content; |
| 28 | + callback(null, file); |
| 29 | + }) |
| 30 | + .catch(err=>{ |
| 31 | + callback(null); |
| 32 | + }); |
| 33 | + return; |
| 34 | + } |
| 35 | + if (file.isStream()){ |
| 36 | + file.contents = file.contents.pipe(new bufferstreams((err, buf, callback)=>{ |
| 37 | + if (err){ |
| 38 | + throw err; |
| 39 | + } |
| 40 | + |
| 41 | + runtcm(filepath, creator, buf.toString(encoding), options) |
| 42 | + .then(content=>{ |
| 43 | + callback(null, content); |
| 44 | + }) |
| 45 | + .catch(err=>{ |
| 46 | + callback(err); |
| 47 | + }); |
| 48 | + })); |
| 49 | + |
| 50 | + callback(null, file); |
| 51 | + return; |
| 52 | + } |
| 53 | + callback(null); |
| 54 | + }); |
| 55 | +}; |
| 56 | + |
| 57 | +function showWarning(file, ...err){ |
| 58 | + gutil.log(gutil.colors.cyan(pluginName), gutil.colors.yellow('Warning'), gutil.colors.gray(file), ...err); |
| 59 | +} |
| 60 | +function showError(...err){ |
| 61 | + gutil.log(gutil.colors.cyan(pluginName), gutil.colors.red('Error'), gutil.colors.gray(file), ...err); |
| 62 | +} |
| 63 | + |
| 64 | +function runtcm(filepath, creator, content, options){ |
| 65 | + return creator.create(filepath, content) |
| 66 | + .then(content=>{ |
| 67 | + if (!options.quiet){ |
| 68 | + for (let mes of content.messageList){ |
| 69 | + showWarning(filepath, mes); |
| 70 | + } |
| 71 | + } |
| 72 | + return new Buffer(content.formatted); |
| 73 | + }) |
| 74 | + .catch(err=>{ |
| 75 | + showError(filepath, err); |
| 76 | + return Promise.reject(err); |
| 77 | + }); |
| 78 | +} |
0 commit comments