|
| 1 | +import path from 'path' |
| 2 | +import rtlcss from 'rtlcss' |
| 3 | +import type { Compiler } from 'webpack' |
| 4 | +import type { ConfigureOptions } from 'rtlcss' |
| 5 | + |
| 6 | +export interface WebpackRTLPluginOptions { |
| 7 | + entries: Set<string> |
| 8 | + rtlcssConfig: ConfigureOptions |
| 9 | + transformFilename: (sourceFilename: string) => string |
| 10 | +} |
| 11 | + |
| 12 | +export class RtlCssPlugin { |
| 13 | + private readonly options: WebpackRTLPluginOptions |
| 14 | + |
| 15 | + private static readonly defaultOptions: WebpackRTLPluginOptions = { |
| 16 | + entries: new Set(), |
| 17 | + rtlcssConfig: {}, |
| 18 | + transformFilename: sourceFilename => |
| 19 | + `${path.parse(sourceFilename).name}-rtl.css` |
| 20 | + } |
| 21 | + |
| 22 | + constructor(options: Partial<WebpackRTLPluginOptions>) { |
| 23 | + this.options = { ...RtlCssPlugin.defaultOptions, ...options } |
| 24 | + } |
| 25 | + |
| 26 | + apply(compiler: Compiler) { |
| 27 | + const { Compilation, sources: { ConcatSource } } = compiler.webpack |
| 28 | + const rtlcssProcessor = rtlcss.configure(this.options.rtlcssConfig) |
| 29 | + |
| 30 | + compiler.hooks.compilation.tap(RtlCssPlugin.name, compilation => { |
| 31 | + compilation.hooks.processAssets.tap({ |
| 32 | + name: RtlCssPlugin.name, |
| 33 | + stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL |
| 34 | + }, assets => { |
| 35 | + for (const chunk of compilation.chunks) { |
| 36 | + if (chunk.name && !this.options.entries.has(chunk.name)) { |
| 37 | + for (const sourceFilename of chunk.files) { |
| 38 | + if ('.css' === path.extname(sourceFilename)) { |
| 39 | + const rtlFilename = this.options.transformFilename(sourceFilename) |
| 40 | + const ltrCss = assets[sourceFilename].source() |
| 41 | + const rtlCss = rtlcssProcessor.process(ltrCss).css |
| 42 | + compilation.emitAsset(rtlFilename, new ConcatSource(rtlCss), { sourceFilename }) |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + }) |
| 48 | + }) |
| 49 | + } |
| 50 | +} |
0 commit comments