|
| 1 | +import type { Plugin, PluginContext, SourceMapInput } from 'rollup'; |
| 2 | +import { Minimatch } from 'minimatch'; |
| 3 | +import postcss from 'postcss'; |
| 4 | +import modules from 'postcss-modules'; |
| 5 | + |
| 6 | +type SeenRecord = { css: string; js: string; json: Record<string, string>; map: SourceMapInput }; |
| 7 | + |
| 8 | +export type PreprocessCSSModulesConfig = { |
| 9 | + include?: string; |
| 10 | + generateScopedName?: (name: string, filename: string, css: string) => string; |
| 11 | + getOutputFilename?: (filename: string) => string; |
| 12 | +}; |
| 13 | + |
| 14 | +export function preprocessCSSModules({ |
| 15 | + include = '**/*.module.css', |
| 16 | + getOutputFilename = (filename: string) => filename.replace(/\.module\.css$/, '.css'), |
| 17 | + generateScopedName, |
| 18 | +}: PreprocessCSSModulesConfig = {}): Plugin<unknown> { |
| 19 | + let seen = new Map<string, SeenRecord>(); |
| 20 | + let includeMatcher = new Minimatch(include, {}); |
| 21 | + |
| 22 | + return { |
| 23 | + name: 'rollup-plugin-preprocess-css-modules', |
| 24 | + |
| 25 | + async resolveId(source, importer, options) { |
| 26 | + let { cssModuleSource } = options.attributes; |
| 27 | + if (cssModuleSource) { |
| 28 | + this.addWatchFile(cssModuleSource); |
| 29 | + return { id: source, meta: { cssModuleSource } }; |
| 30 | + } else { |
| 31 | + let file = await this.resolve(source, importer, { ...options, skipSelf: true }); |
| 32 | + if (file && includeMatcher.match(file.id)) { |
| 33 | + return { ...file, id: `${file.id}.js`, meta: { ...file.meta, cssModule: true } }; |
| 34 | + } |
| 35 | + } |
| 36 | + }, |
| 37 | + |
| 38 | + async load(id) { |
| 39 | + let meta = this.getModuleInfo(id)?.meta; |
| 40 | + if (meta?.cssModuleSource) { |
| 41 | + return seen.get(meta.cssModuleSource)?.css; |
| 42 | + } else if (meta?.cssModule) { |
| 43 | + let result = await processModule(this, id); |
| 44 | + return result.js; |
| 45 | + } |
| 46 | + }, |
| 47 | + }; |
| 48 | + |
| 49 | + async function processModule(ctx: PluginContext, id: string): Promise<SeenRecord> { |
| 50 | + let inputPath = id.replace(/\.js$/, ''); |
| 51 | + let outputPath = getOutputFilename(inputPath); |
| 52 | + let rawContent = await ctx.fs.readFile(inputPath, { encoding: 'utf8' }); |
| 53 | + let js: string | undefined, json: Record<string, string> | undefined; |
| 54 | + let processor = postcss([ |
| 55 | + modules({ |
| 56 | + generateScopedName, |
| 57 | + Loader: class { |
| 58 | + async fetch(path: string, fromModule: string) { |
| 59 | + let resolved = await ctx.resolve(path, fromModule, { skipSelf: false }); |
| 60 | + if (resolved) await ctx.load(resolved); |
| 61 | + return ( |
| 62 | + seen.get(resolved?.id.replace(/\.js$/, '') ?? '')?.json ?? |
| 63 | + ctx.error('Internal error: CSS module mapping not found') |
| 64 | + ); |
| 65 | + } |
| 66 | + }, |
| 67 | + getJSON: (inputFilename, mapping) => { |
| 68 | + if (inputFilename === inputPath) { |
| 69 | + json = mapping; |
| 70 | + js = [ |
| 71 | + `import ${JSON.stringify(outputPath)} with { cssModuleSource: ${JSON.stringify(inputPath)} };`, |
| 72 | + `export default ${JSON.stringify(json)};`, |
| 73 | + ].join('\n'); |
| 74 | + } |
| 75 | + }, |
| 76 | + }), |
| 77 | + ]); |
| 78 | + |
| 79 | + let { css, map } = await processor.process(rawContent, { from: inputPath, to: outputPath }); |
| 80 | + if (!js || !json) { |
| 81 | + throw new Error(`Failed to process CSS module: ${inputPath}`); |
| 82 | + } |
| 83 | + |
| 84 | + let result = { js, json, css, map: map?.toJSON() as SourceMapInput }; |
| 85 | + seen.set(inputPath, result); |
| 86 | + return result; |
| 87 | + } |
| 88 | +} |
0 commit comments