Skip to content

Commit 378a5df

Browse files
committed
feat: Use Rolldown native MagicString
1 parent cd26b63 commit 378a5df

File tree

1 file changed

+27
-5
lines changed
  • packages/bundler-plugin-core/src

1 file changed

+27
-5
lines changed

packages/bundler-plugin-core/src/index.ts

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -232,10 +232,12 @@ type RenderChunkHook = (
232232
chunk: {
233233
fileName: string;
234234
facadeModuleId?: string | null;
235-
}
235+
},
236+
outputOptions?: unknown,
237+
meta?: { magicString?: MagicString }
236238
) => {
237239
code: string;
238-
map: SourceMap;
240+
readonly map?: SourceMap;
239241
} | null;
240242

241243
/**
@@ -292,7 +294,12 @@ export function createRollupInjectionHooks(
292294
renderChunk: RenderChunkHook;
293295
} {
294296
return {
295-
renderChunk(code: string, chunk: { fileName: string; facadeModuleId?: string | null }) {
297+
renderChunk(
298+
code: string,
299+
chunk: { fileName: string; facadeModuleId?: string | null },
300+
_?: unknown,
301+
meta?: { magicString?: MagicString }
302+
) {
296303
if (!isJsFile(chunk.fileName)) {
297304
return null; // returning null means not modifying the chunk at all
298305
}
@@ -320,7 +327,11 @@ export function createRollupInjectionHooks(
320327
}
321328
}
322329

323-
const ms = new MagicString(code, { filename: chunk.fileName });
330+
if (codeToInject === "") {
331+
return null;
332+
}
333+
334+
const ms = meta?.magicString || new MagicString(code, { filename: chunk.fileName });
324335
const match = code.match(COMMENT_USE_STRICT_REGEX)?.[0];
325336

326337
if (match) {
@@ -333,9 +344,20 @@ export function createRollupInjectionHooks(
333344
ms.prepend(codeToInject);
334345
}
335346

347+
// Rolldown can pass a native MagicString instance in meta.magicString
348+
if (ms?.constructor?.name === "BindingMagicString") {
349+
// Rolldown docs say to return the magic string instance directly in this case
350+
return { code: ms as unknown as string };
351+
}
352+
336353
return {
337354
code: ms.toString(),
338-
map: ms.generateMap({ file: chunk.fileName, hires: "boundary" }),
355+
get map() {
356+
return ms.generateMap({
357+
file: chunk.fileName,
358+
hires: "boundary",
359+
});
360+
},
339361
};
340362
},
341363
};

0 commit comments

Comments
 (0)