mergeLessPlugin.js 2.12 KB
Newer Older
陈帅's avatar
陈帅 committed
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
#!/usr/bin/env node
/**
 * 这个方法用来处理 css-modlue
 * 由于没有开源插件,所以自己撸了一个
 */

const fs = require('fs');
const path = require('path');
const getLocalIdentName = require('./getLocalIdentName');
const AddlocalIdentName = require('./AddlocalIdentName');
const replacedefaultLess = require('./replacedefaultLess');
// read less file list
const lessArray = ['@import "../node_modules/antd/lib/style/themes/default.less";'];

const loopAllLess = parents => {
  const paths = fs.readdirSync(parents);
  const promiseList = [];
  paths.forEach(itemPath => {
    if (itemPath === 'style' || itemPath === 'demo') {
      return;
    }
    // file status
    const fileStatus = fs.lstatSync(path.join(parents, itemPath));
    // is file
    // is Directory
    if (fileStatus.isDirectory()) {
      return loopAllLess(path.join(parents, itemPath));
    }
    // is less file
    if (itemPath.indexOf('.less') > -1) {
      const relaPath = path.join(parents, itemPath);
      // post css add localIdentNameplugin
      const fileContent = replacedefaultLess(relaPath);
      // push less file
      promiseList.push(
        AddlocalIdentName(relaPath, fileContent, getLocalIdentName(relaPath)).then(result => {
          lessArray.push(result);
        })
      );
    }
  });
  return Promise.all(promiseList);
};

class mergeLessPlugin {
  constructor(options) {
    const defaulOptions = {
      stylesDir: path.join(__dirname, './src/'),
      outFile: path.join(__dirname, './tmp/ant.design.pro.less'),
    };
    this.options = Object.assign(defaulOptions, options);
    this.generated = false;
  }

  apply(compiler) {
    const { options } = this;
    compiler.plugin('emit', (compilation, callback) => {
      const { outFile } = options;
      // covert less
      if (fs.existsSync(outFile)) {
        fs.unlinkSync(outFile);
陈帅's avatar
陈帅 committed
62
      } else if (!fs.existsSync(path.dirname(outFile))) {
wangyun's avatar
wangyun committed
63
        fs.mkdirSync(path.dirname(outFile));
陈帅's avatar
陈帅 committed
64 65 66 67 68 69 70 71 72 73
      }
      loopAllLess(options.stylesDir).then(() => {
        fs.writeFileSync(outFile, lessArray.join('\n'));
        callback();
      });
    });
  }
}

module.exports = mergeLessPlugin;