diff --git a/src/esbuild/postcss.ts b/src/esbuild/postcss.ts index 49ec0383..3c2075bc 100644 --- a/src/esbuild/postcss.ts +++ b/src/esbuild/postcss.ts @@ -2,7 +2,7 @@ import fs from 'fs' import path from 'path' import { Loader, Plugin, transform } from 'esbuild' import { getPostcss } from '../utils' -import type { Result } from 'postcss-load-config'; +import type { Result } from 'postcss-load-config' export const postcssPlugin = ({ css, @@ -10,7 +10,7 @@ export const postcssPlugin = ({ cssLoader, }: { css?: Map - inject?: boolean + inject?: boolean | ((css: string, fileId: string) => string) cssLoader?: Loader }): Plugin => { return { @@ -28,7 +28,7 @@ export const postcssPlugin = ({ try { const result = await loadConfig({}, process.cwd()) - configCache = result + configCache = result return result } catch (error: any) { if (error.message.includes('No PostCSS Config found in')) { @@ -123,9 +123,12 @@ export const postcssPlugin = ({ }) ).code - contents = `import styleInject from '#style-inject';styleInject(${JSON.stringify( - contents - )})` + contents = + typeof inject === 'function' + ? inject(JSON.stringify(contents), args.path) + : `import styleInject from '#style-inject';styleInject(${JSON.stringify( + contents + )})` return { contents, diff --git a/src/options.ts b/src/options.ts index 067f4444..fc3c2afa 100644 --- a/src/options.ts +++ b/src/options.ts @@ -197,7 +197,7 @@ export type Options = { * Inject CSS as style tags to document head * @default {false} */ - injectStyle?: boolean + injectStyle?: boolean | ((css: string, fileId: string) => string) /** * Inject cjs and esm shims if needed * @default false diff --git a/test/index.test.ts b/test/index.test.ts index f2a740ac..9e7c71e8 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -1245,3 +1245,25 @@ test(`should generate export {} when there are no exports in source file`, async expect(outFiles).toEqual(['input.d.ts', 'input.mjs']) expect(await getFileContent('dist/input.d.ts')).toContain('export { }') }) + +test('custom inject style function', async () => { + const { outFiles, getFileContent } = await run( + getTestName(), + { + 'input.ts': `import './style.css'`, + 'style.css': `.hello { color: red }`, + 'tsup.config.ts': ` + export default { + entry: ['src/input.ts'], + minify: true, + format: ['esm', 'cjs'], + injectStyle: (css) => { + return "__custom_inject_style__(" + css +")"; + } + }`, + }, + ) + expect(outFiles).toEqual(['input.js', 'input.mjs']) + expect(await getFileContent('dist/input.mjs')).toContain('__custom_inject_style__(`.hello{color:red}\n`)') + expect(await getFileContent('dist/input.js')).toContain('__custom_inject_style__(`.hello{color:red}\n`)') +}) \ No newline at end of file