Skip to content

Commit f7ac3bd

Browse files
authored
feat: Use Rolldown native MagicString (#846)
* feat: Use Rolldown native `MagicString` * Add docs link
1 parent 78ce650 commit f7ac3bd

File tree

1 file changed

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

1 file changed

+24
-5
lines changed

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

Lines changed: 24 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,7 @@ export function createRollupInjectionHooks(
320327
}
321328
}
322329

323-
const ms = new MagicString(code, { filename: chunk.fileName });
330+
const ms = meta?.magicString || new MagicString(code, { filename: chunk.fileName });
324331
const match = code.match(COMMENT_USE_STRICT_REGEX)?.[0];
325332

326333
if (match) {
@@ -333,9 +340,21 @@ export function createRollupInjectionHooks(
333340
ms.prepend(codeToInject);
334341
}
335342

343+
// Rolldown can pass a native MagicString instance in meta.magicString
344+
// https://rolldown.rs/in-depth/native-magic-string#usage-examples
345+
if (ms?.constructor?.name === "BindingMagicString") {
346+
// Rolldown docs say to return the magic string instance directly in this case
347+
return { code: ms as unknown as string };
348+
}
349+
336350
return {
337351
code: ms.toString(),
338-
map: ms.generateMap({ file: chunk.fileName, hires: "boundary" }),
352+
get map() {
353+
return ms.generateMap({
354+
file: chunk.fileName,
355+
hires: "boundary",
356+
});
357+
},
339358
};
340359
},
341360
};

0 commit comments

Comments
 (0)