mergeLessPlugin.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env node
  2. /**
  3. * 这个方法用来处理 css-modlue
  4. * 由于没有开源插件,所以自己撸了一个
  5. */
  6. const fs = require('fs');
  7. const path = require('path');
  8. const getLocalIdentName = require('./getLocalIdentName');
  9. const AddlocalIdentName = require('./AddlocalIdentName');
  10. const replacedefaultLess = require('./replacedefaultLess');
  11. // read less file list
  12. const lessArray = ['@import "../node_modules/antd/lib/style/themes/default.less";'];
  13. const loopAllLess = parents => {
  14. const paths = fs.readdirSync(parents);
  15. const promiseList = [];
  16. paths.forEach(itemPath => {
  17. if (itemPath === 'style' || itemPath === 'demo') {
  18. return;
  19. }
  20. // file status
  21. const fileStatus = fs.lstatSync(path.join(parents, itemPath));
  22. // is file
  23. // is Directory
  24. if (fileStatus.isDirectory()) {
  25. return loopAllLess(path.join(parents, itemPath));
  26. }
  27. // is less file
  28. if (itemPath.indexOf('.less') > -1) {
  29. const relaPath = path.join(parents, itemPath);
  30. // post css add localIdentNameplugin
  31. const fileContent = replacedefaultLess(relaPath);
  32. // push less file
  33. promiseList.push(
  34. AddlocalIdentName(relaPath, fileContent, getLocalIdentName(relaPath)).then(result => {
  35. lessArray.push(result);
  36. })
  37. );
  38. }
  39. });
  40. return Promise.all(promiseList);
  41. };
  42. class mergeLessPlugin {
  43. constructor(options) {
  44. const defaulOptions = {
  45. stylesDir: path.join(__dirname, './src/'),
  46. outFile: path.join(__dirname, './tmp/ant.design.pro.less'),
  47. };
  48. this.options = Object.assign(defaulOptions, options);
  49. this.generated = false;
  50. }
  51. apply(compiler) {
  52. const { options } = this;
  53. compiler.plugin('emit', (compilation, callback) => {
  54. const { outFile } = options;
  55. // covert less
  56. if (fs.existsSync(outFile)) {
  57. fs.unlinkSync(outFile);
  58. } else if (!fs.existsSync(path.dirname(outFile))) {
  59. fs.mkdirSync(path.dirname(outFile));
  60. }
  61. loopAllLess(options.stylesDir).then(() => {
  62. fs.writeFileSync(outFile, lessArray.join('\n'));
  63. callback();
  64. });
  65. });
  66. }
  67. }
  68. module.exports = mergeLessPlugin;