@@ -3,7 +3,7 @@ import path from 'node:path'
33import { createUnplugin , type UnpluginInstance } from 'unplugin'
44import { createFilter } from 'unplugin-utils'
55import { resolveOptions , type Options } from './core/options'
6- import type { Loader } from 'esbuild'
6+ import type { Loader , TransformOptions } from 'esbuild'
77import type { PluginContext } from 'rollup'
88
99const unplugin : UnpluginInstance < Options | undefined , false > = createUnplugin (
@@ -43,32 +43,32 @@ const unplugin: UnpluginInstance<Options | undefined, false> = createUnplugin(
4343
4444 load : {
4545 filter : { id : { include : rawRE } } ,
46- async handler ( id ) {
46+ handler ( id ) {
4747 const file = cleanUrl ( id )
48- let contents = await readFile ( file , 'utf-8' )
49- if ( transformFilter ( file ) ) {
50- let transform : typeof import ( 'esbuild' ) . transform
51- const nativeContext = this . getNativeBuildContext ?.( )
52- if ( nativeContext ?. framework === 'esbuild' ) {
53- ; ( { transform } = nativeContext . build . esbuild )
54- } else {
55- transform = ( await import ( 'esbuild' ) ) . transform
56- }
57- contents = (
58- await transform ( contents , {
59- loader : guessLoader ( file ) ,
60- ...options . transform . options ,
61- } )
62- ) . code
63- }
64- return `export default ${ JSON . stringify ( contents ) } `
48+ const context = this . getNativeBuildContext ?.( )
49+ const transform =
50+ context ?. framework === 'esbuild'
51+ ? context . build . esbuild . transform
52+ : undefined
53+ return transformRaw (
54+ file ,
55+ transformFilter ,
56+ options . transform . options ,
57+ transform ,
58+ )
6559 } ,
6660 } ,
6761 esbuild : {
6862 setup ( build ) {
69- build . onLoad ( { filter : / .* / } , ( args ) => {
63+ build . onLoad ( { filter : / .* / } , async ( args ) => {
7064 if ( args . with . type === 'text' ) {
71- return { contents : 'export default "123"' }
65+ const contents = await transformRaw (
66+ args . path ,
67+ transformFilter ,
68+ options . transform . options ,
69+ build . esbuild . transform ,
70+ )
71+ return { contents, loader : 'js' }
7272 }
7373 } )
7474 } ,
@@ -105,3 +105,20 @@ const ExtToLoader: Record<string, Loader> = {
105105export function guessLoader ( id : string ) : Loader {
106106 return ExtToLoader [ path . extname ( id ) . toLowerCase ( ) ] || 'js'
107107}
108+
109+ async function transformRaw (
110+ file : string ,
111+ transformFilter : ( id : string | unknown ) => boolean ,
112+ options : TransformOptions ,
113+ transform ?: typeof import ( 'esbuild' ) . transform ,
114+ ) {
115+ let contents = await readFile ( file , 'utf-8' )
116+
117+ if ( transformFilter ( file ) ) {
118+ transform ||= ( await import ( 'esbuild' ) ) . transform
119+ contents = (
120+ await transform ( contents , { loader : guessLoader ( file ) , ...options } )
121+ ) . code
122+ }
123+ return `export default ${ JSON . stringify ( contents ) } `
124+ }
0 commit comments