theme-less.js 1.17 KB

const { relative, dirname } = require("path");
const { Buffer } = require('buffer');
const through = require('through2');
const fs = require("fs");
const gutil = require('gulp-util');
const PluginError = gutil.PluginError;

const PLUGIN_NAME = 'theme-less';

function themeLess(settings) {
    if (!settings) {
        throw new PluginError(PLUGIN_NAME, 'Missing settings!');
    }

    return through.obj(function (file, enc, cb) {
        if (file.isNull()) {
            cb(null, file);
        }

        if (file.isStream()) {
            throw new PluginError(PLUGIN_NAME, 'Can not support Streaming!');
        }

        const { path } = settings;

        if (path && fs.existsSync(path)) {
            fs.createReadStream(path)
                .pipe(through.obj(function () {
                    const relPath = relative(dirname(file.path), path);
                    const impBuffer = new Buffer(`@import (reference) "${relPath}";\n`);
                    
                    file.contents = Buffer.concat([impBuffer, file.contents]);
                    cb(null, file);
                }));
        } else {
            cb(null, file);
        }
    });

};

module.exports = themeLess;