|
| 1 | +import { Plugin } from "esbuild"; |
| 2 | +import fs from "node:fs"; |
| 3 | +import path from "node:path"; |
| 4 | +import postcss from "postcss"; |
| 5 | +import postcssModules from "postcss-modules"; |
| 6 | +import autoPrefixer from "autoprefixer"; |
| 7 | + |
| 8 | +const cssModulePlugin: () => Plugin = () => ({ |
| 9 | + name: "esbuild-plugin-react18-css-" + uuid(), |
| 10 | + setup(build): void { |
| 11 | + build.onResolve({ filter: /\.module\.css$/, namespace: "file" }, args => ({ |
| 12 | + path: `${args.path}#css-module`, |
| 13 | + namespace: "css-module", |
| 14 | + pluginData: { |
| 15 | + pathDir: path.join(args.resolveDir, args.path), |
| 16 | + }, |
| 17 | + })); |
| 18 | + build.onLoad({ filter: /#css-module$/, namespace: "css-module" }, async args => { |
| 19 | + const { pluginData } = args as { |
| 20 | + pluginData: { pathDir: string }; |
| 21 | + }; |
| 22 | + |
| 23 | + const source = fs.readFileSync(pluginData.pathDir, "utf8"); |
| 24 | + |
| 25 | + let cssModule = {}; |
| 26 | + const result = await postcss([ |
| 27 | + postcssModules({ |
| 28 | + getJSON(_, json) { |
| 29 | + cssModule = json; |
| 30 | + }, |
| 31 | + generateScopedName: "[name]__[local]", |
| 32 | + }), |
| 33 | + autoPrefixer, |
| 34 | + ]).process(source, { from: pluginData.pathDir }); |
| 35 | + |
| 36 | + return { |
| 37 | + pluginData: { css: result.css }, |
| 38 | + contents: `import "${pluginData.pathDir}"; export default ${JSON.stringify(cssModule)}`, |
| 39 | + }; |
| 40 | + }); |
| 41 | + |
| 42 | + /** apply auto-prefixer to css */ |
| 43 | + |
| 44 | + build.onLoad({ filter: /\.css$/, namespace: "file" }, async args => { |
| 45 | + const source = fs.readFileSync(args.path, "utf8"); |
| 46 | + const result = await postcss([autoPrefixer]).process(source, { from: args.path }); |
| 47 | + console.log("CSS ------------------------------------ ", result.css); |
| 48 | + return { contents: result.css, loader: "css" }; |
| 49 | + }); |
| 50 | + |
| 51 | + build.onResolve({ filter: /\.module\.css$/, namespace: "css-module" }, args => ({ |
| 52 | + path: path.join(args.resolveDir, args.path, "#css-module-data"), |
| 53 | + namespace: "css-module", |
| 54 | + pluginData: args.pluginData as { css: string }, |
| 55 | + })); |
| 56 | + |
| 57 | + build.onLoad({ filter: /#css-module-data$/, namespace: "css-module" }, args => ({ |
| 58 | + contents: (args.pluginData as { css: string }).css, |
| 59 | + loader: "css", |
| 60 | + })); |
| 61 | + }, |
| 62 | +}); |
| 63 | + |
| 64 | +const uuid = () => (Date.now() * Math.random()).toString(36).slice(0, 8); |
| 65 | + |
| 66 | +export = cssModulePlugin; |
0 commit comments