Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const path = require('path');
- const fs = require('fs');
- const postcss = require('postcss');
- const postcssCustomProperties = require('postcss-custom-properties');
- const postcssDiscardComments = require('postcss-discard-comments');
- /**
- * Плагин к webpack для создания css bundle с подставленными цветами из темы.
- */
- class ApplyCssVariablesWebpackPlugin {
- /**
- * Конструктор.
- * @param {string} outputFolder Путь для сохранения нового файла.
- * @param {string} bundleName Начало названия css bundle, который нужно преобразовать.
- */
- constructor(outputFolder, bundleName) {
- this.outputFolder = outputFolder;
- this.bundleName = bundleName;
- }
- /**
- * Применяет css переменные к css-файлу. Сейчас только для appStyles.
- * @param {Object} compilation
- * @param {string} themeVariables Переменные темы.
- * @param {string} postfix Постфикс, который добавится в имя нового css-файла.
- */
- async _applyCssVariables(compilation, themeVariables, postfix) {
- const bundleAsset = this._findAsset(compilation, this.bundleName);
- if (bundleAsset != null) {
- const bundleContent = bundleAsset.source();
- const bundleFilePath = bundleAsset.existsAt;
- const bundleFileName = path.basename(bundleFilePath);
- const newBundleFilePath = path.join(this.outputFolder, `${bundleFileName}.${postfix}.css`);
- // Подставляем css переменные в итоговый css
- const result = await postcss([
- postcssCustomProperties({ preserve: false }),
- postcssDiscardComments(),
- ]).process(themeVariables + '\r\n' + bundleContent, { from: bundleFilePath, to: newBundleFilePath });
- fs.writeFileSync(newBundleFilePath, result.css);
- }
- }
- /**
- * Найти asset имя которого начинается с startWith.
- * @param {Object} compilation
- * @param {string} startWith Начало asset.
- * @returns {Object} Asset.
- */
- _findAsset(compilation, startWith) {
- const key = Object.keys(compilation.assets).find(k => k.indexOf(startWith) >= 0 && k.indexOf('.css') >= 0);
- return key != null ? compilation.assets[key] : null;
- }
- /**
- * Главная функция webpack-плагина.
- * @param {Object} compiler Объект компилятора webpack для перехвата событий процесса сборки bundle.
- */
- apply(compiler) {
- compiler.hooks.afterEmit.tapPromise('ApplyCssVariablesWebpackPlugin', (compilation) => {
- let themeVariables;
- const themeAsset = this._findAsset(compilation, 'theme-default_');
- if (themeAsset != null) {
- themeVariables = themeAsset.source();
- }
- else {
- const themeFilePath = path.resolve('src/styles/themes/theme-default.css');
- themeVariables = fs.readFileSync(themeFilePath).toString();
- }
- return this._applyCssVariables(compilation, themeVariables, 'ie');
- });
- }
- }
- module.exports = ApplyCssVariablesWebpackPlugin;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement