feat(script/jsx): support import syntax for preact

This commit is contained in:
Elian Doran 2025-12-20 22:14:36 +02:00
parent 284b66acd2
commit 6c1b327f5f
No known key found for this signature in database
2 changed files with 33 additions and 1 deletions

View File

@ -145,4 +145,25 @@ describe("JSX building", () => {
`;
expect(buildJsx(script).code).toStrictEqual(expected);
});
it("rewrite React API imports", () => {
const script = trimIndentation`\
import { defineWidget, RightPanelWidget} from "trilium:preact";
defineWidget({
render() {
return <RightPanelWidget />;
}
});
`;
const expected = trimIndentation`\
"use strict";const _jsxFileName = "";const _triliumpreact = api.preact;
_triliumpreact.defineWidget.call(void 0, {
render() {
return api.preact.h(_triliumpreact.RightPanelWidget, {__self: this, __source: {fileName: _jsxFileName, lineNumber: 4}} );
}
});
`;
console.log(buildJsx(script).code);
expect(buildJsx(script).code).toStrictEqual(expected);
});
});

View File

@ -226,10 +226,21 @@ export function buildJsx(contentRaw: string | Buffer) {
jsxFragmentPragma: "api.preact.Fragment",
});
output.code = output.code.replaceAll(
let code = output.code;
// Rewrite ESM-like exports to `module.exports =`.
code = output.code.replaceAll(
/\bexports\s*\.\s*default\s*=\s*/g,
'module.exports = '
);
// Rewrite ESM-like imports to Preact, to `const { foo } = api.preact`
code = code.replaceAll(
/var\s+(\w+)\s*=\s*require\(['"]trilium:preact['"]\);?/g,
'const $1 = api.preact;'
);
output.code = code;
return output;
}