|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import path from "node:path"; |
| 3 | +import postcss, { type AcceptedPlugin } from "postcss"; |
| 4 | +import type { Plugin } from "esbuild"; |
| 5 | + |
| 6 | +export interface PostCssPluginOptions { |
| 7 | + plugins?: AcceptedPlugin[]; |
| 8 | +} |
| 9 | + |
| 10 | +export default function postCssPlugin( |
| 11 | + options: PostCssPluginOptions = {}, |
| 12 | +): Plugin { |
| 13 | + const plugins = options.plugins ?? []; |
| 14 | + |
| 15 | + return { |
| 16 | + name: "postcss", |
| 17 | + setup(build) { |
| 18 | + build.onResolve({ filter: /\.css$/, namespace: "file" }, async (args) => { |
| 19 | + // Use esbuild path resolution for node_modules, tsconfig paths, etc. |
| 20 | + // https://esbuild.github.io/plugins/#resolve |
| 21 | + const resolution = await build.resolve(args.path, { |
| 22 | + resolveDir: args.resolveDir, |
| 23 | + kind: args.kind, |
| 24 | + }); |
| 25 | + |
| 26 | + if (resolution.errors.length > 0) { |
| 27 | + return { errors: resolution.errors }; |
| 28 | + } |
| 29 | + |
| 30 | + return { |
| 31 | + path: resolution.path, |
| 32 | + namespace: "postcss", |
| 33 | + }; |
| 34 | + }); |
| 35 | + |
| 36 | + build.onLoad( |
| 37 | + { filter: /\.css$/, namespace: "postcss" }, |
| 38 | + async (args) => { |
| 39 | + const sourceFullPath = args.path; |
| 40 | + const css = await fs.readFile(sourceFullPath, "utf8"); |
| 41 | + |
| 42 | + if (plugins.length === 0) { |
| 43 | + return { |
| 44 | + contents: css, |
| 45 | + loader: "css", |
| 46 | + resolveDir: path.dirname(sourceFullPath), |
| 47 | + watchFiles: [sourceFullPath], |
| 48 | + }; |
| 49 | + } |
| 50 | + |
| 51 | + const result = await postcss(plugins).process(css, { |
| 52 | + from: sourceFullPath, |
| 53 | + }); |
| 54 | + |
| 55 | + return { |
| 56 | + contents: result.css, |
| 57 | + loader: "css", |
| 58 | + resolveDir: path.dirname(sourceFullPath), |
| 59 | + watchFiles: [sourceFullPath], |
| 60 | + }; |
| 61 | + }, |
| 62 | + ); |
| 63 | + }, |
| 64 | + }; |
| 65 | +} |
0 commit comments