Skip to content

Instantly share code, notes, and snippets.

@artem-malko
Last active November 18, 2019 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artem-malko/e70fd3920f4e13e02e1f3bcb5a1efff0 to your computer and use it in GitHub Desktop.
Save artem-malko/e70fd3920f4e13e02e1f3bcb5a1efff0 to your computer and use it in GitHub Desktop.
Webpack css-in-js plugin
import { Plugin, Compiler } from 'webpack';
import { ConcatSource } from 'webpack-sources';
const loaderUtils = require('loader-utils');
const Chunk = require('webpack/lib/Chunk');
import { storeInstance } from '../store';
import { generateCss } from '../../generator';
import { StylesDescriptor } from '../../generator/utils';
export class CSSInJSPlugin implements Plugin {
public apply(compiler: Compiler) {
compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation) => {
compilation.hooks.additionalAssets.tap(this.constructor.name, () => {
const styleDescriptors = storeInstance.getStyles();
const styleDescriptorsWithSortedStyles = Object.keys(styleDescriptors)
.sort()
.reduce<{ [key: string]: StylesDescriptor }>((result, styleDescriptorHash) => {
result[styleDescriptorHash] = styleDescriptors[styleDescriptorHash];
return result;
}, {});
const rtlStyles = generateCss(styleDescriptorsWithSortedStyles, 'rtl');
const ltrStyles = generateCss(styleDescriptorsWithSortedStyles, 'ltr');
const rtlChunk = new Chunk('stylesRtl');
const ltrChunk = new Chunk('stylesLtr');
const ltrFileName = loaderUtils.interpolateName({}, 'styles.ltr.[contenthash].css', {
content: ltrStyles,
});
const rtlFileName = loaderUtils.interpolateName({}, 'styles.rtl.[contenthash].css', {
content: rtlStyles,
});
ltrChunk.ids = [];
// @TODO change types
(ltrChunk.files as any).add(ltrFileName);
rtlChunk.ids = [];
// @TODO change types
(rtlChunk.files as any).add(rtlFileName);
// Add renderedSprite to compilation resources
// @TODO use https://github.com/webpack/webpack-sources
const ltrSource = new ConcatSource();
ltrSource.add(ltrStyles);
compilation.assets[ltrFileName] = ltrSource;
// @TODO change types
(compilation.chunks as any).add(ltrChunk);
const rtlSource = new ConcatSource();
rtlSource.add(rtlStyles);
compilation.assets[rtlFileName] = rtlSource;
// @TODO change types
(compilation.chunks as any).add(rtlChunk);
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment