diff --git a/src/helpers.ts b/src/helpers.ts index ceadc7d..b6cd80f 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -1,22 +1,22 @@ import { transformWithEsbuild } from 'vite' import { grants } from './constants.js' import type { Grants, Transform } from './types.js' +import type { EsbuildTransformOptions } from 'vite' export function removeDuplicates(arr: any): any[] { return [...new Set(Array.isArray(arr) ? arr : arr ? [arr] : [])] } -export async function transform({ - minify, - file, - name, - loader -}: Transform): Promise { +export async function transform( + { minify, file, name, loader }: Transform, + transformOptions?: EsbuildTransformOptions +): Promise { const { code } = await transformWithEsbuild(file, name, { minify, loader, sourcemap: false, - legalComments: 'none' + legalComments: 'none', + ...transformOptions }) return code diff --git a/src/index.ts b/src/index.ts index 8313137..66b77b9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -148,12 +148,15 @@ export default function UserscriptPlugin( try { let source = readFileSync(outPath, 'utf8') source = source.replace(styleTemplate, `${css.inject()}`) - source = await transform({ - minify: !isBuildWatch, - file: source, - name: fileName, - loader: 'js' - }) + source = await transform( + { + minify: !isBuildWatch, + file: source, + name: fileName, + loader: 'js' + }, + config.esbuildTransformOptions + ) config.header.grant = removeDuplicates( isBuildWatch @@ -164,12 +167,15 @@ export default function UserscriptPlugin( if (isBuildWatch) { const wsFile = readFileSync(resolve(pluginDir, 'ws.js'), 'utf8') - const wsScript = await transform({ - minify: !isBuildWatch, - file: wsFile.replace('__WS__', `ws://localhost:${port}`), - name: wsPath, - loader: 'js' - }) + const wsScript = await transform( + { + minify: !isBuildWatch, + file: wsFile.replace('__WS__', `ws://localhost:${port}`), + name: wsPath, + loader: 'js' + }, + config.esbuildTransformOptions + ) writeFileSync(wsPath, wsScript) writeFileSync( diff --git a/src/types.ts b/src/types.ts index 9068d07..b75e37e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,5 @@ import { GM, GMwindow } from './constants.js' +import type { EsbuildTransformOptions } from 'vite' export interface Transform { minify: boolean @@ -217,4 +218,20 @@ export interface UserscriptPluginConfig { * Server config. */ server?: ServerConfig + + /** + * Override default esbuild transform options. + * + * @default + * ```json + * { + * "minify": true, + * "legalComments": "none" + * } + * ``` + */ + esbuildTransformOptions?: Omit< + EsbuildTransformOptions, + 'format' | 'target' | 'loader' | 'sourcemap' + > }