Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.12 KB | None | 0 0
  1. const path = require('path');
  2. const fs = require('fs');
  3. const postcss = require('postcss');
  4. const postcssCustomProperties = require('postcss-custom-properties');
  5. const postcssDiscardComments = require('postcss-discard-comments');
  6.  
  7. /**
  8. * Плагин к webpack для создания css bundle с подставленными цветами из темы.
  9. */
  10. class ApplyCssVariablesWebpackPlugin {
  11.  
  12. /**
  13. * Конструктор.
  14. * @param {string} outputFolder Путь для сохранения нового файла.
  15. * @param {string} bundleName Начало названия css bundle, который нужно преобразовать.
  16. */
  17. constructor(outputFolder, bundleName) {
  18. this.outputFolder = outputFolder;
  19. this.bundleName = bundleName;
  20. }
  21.  
  22. /**
  23. * Применяет css переменные к css-файлу. Сейчас только для appStyles.
  24. * @param {Object} compilation
  25. * @param {string} themeVariables Переменные темы.
  26. * @param {string} postfix Постфикс, который добавится в имя нового css-файла.
  27. */
  28. async _applyCssVariables(compilation, themeVariables, postfix) {
  29. const bundleAsset = this._findAsset(compilation, this.bundleName);
  30. if (bundleAsset != null) {
  31. const bundleContent = bundleAsset.source();
  32. const bundleFilePath = bundleAsset.existsAt;
  33. const bundleFileName = path.basename(bundleFilePath);
  34. const newBundleFilePath = path.join(this.outputFolder, `${bundleFileName}.${postfix}.css`);
  35.  
  36. // Подставляем css переменные в итоговый css
  37. const result = await postcss([
  38. postcssCustomProperties({ preserve: false }),
  39. postcssDiscardComments(),
  40. ]).process(themeVariables + '\r\n' + bundleContent, { from: bundleFilePath, to: newBundleFilePath });
  41.  
  42. fs.writeFileSync(newBundleFilePath, result.css);
  43. }
  44. }
  45.  
  46. /**
  47. * Найти asset имя которого начинается с startWith.
  48. * @param {Object} compilation
  49. * @param {string} startWith Начало asset.
  50. * @returns {Object} Asset.
  51. */
  52. _findAsset(compilation, startWith) {
  53. const key = Object.keys(compilation.assets).find(k => k.indexOf(startWith) >= 0 && k.indexOf('.css') >= 0);
  54. return key != null ? compilation.assets[key] : null;
  55. }
  56.  
  57. /**
  58. * Главная функция webpack-плагина.
  59. * @param {Object} compiler Объект компилятора webpack для перехвата событий процесса сборки bundle.
  60. */
  61. apply(compiler) {
  62. compiler.hooks.afterEmit.tapPromise('ApplyCssVariablesWebpackPlugin', (compilation) => {
  63. let themeVariables;
  64. const themeAsset = this._findAsset(compilation, 'theme-default_');
  65. if (themeAsset != null) {
  66. themeVariables = themeAsset.source();
  67. }
  68. else {
  69. const themeFilePath = path.resolve('src/styles/themes/theme-default.css');
  70. themeVariables = fs.readFileSync(themeFilePath).toString();
  71. }
  72. return this._applyCssVariables(compilation, themeVariables, 'ie');
  73. });
  74. }
  75. }
  76.  
  77.  
  78. module.exports = ApplyCssVariablesWebpackPlugin;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement