Skip to content

Commit

Permalink
feat: add function type for options.injectStyle (#855)
Browse files Browse the repository at this point in the history
  • Loading branch information
await-ovo committed Mar 19, 2023
1 parent 97f3abf commit 01169b3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
15 changes: 9 additions & 6 deletions src/esbuild/postcss.ts
Expand Up @@ -2,15 +2,15 @@ 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,
inject,
cssLoader,
}: {
css?: Map<string, string>
inject?: boolean
inject?: boolean | ((css: string, fileId: string) => string)
cssLoader?: Loader
}): Plugin => {
return {
Expand All @@ -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')) {
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/options.ts
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions test/index.test.ts
Expand Up @@ -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`)')
})

0 comments on commit 01169b3

Please sign in to comment.