feat(script/jsx): support export default syntax

This commit is contained in:
Elian Doran 2025-12-20 21:58:57 +02:00
parent dcd73ff9f9
commit 284b66acd2
No known key found for this signature in database
2 changed files with 34 additions and 4 deletions

View File

@ -95,7 +95,7 @@ describe("JSX building", () => {
}
`;
const expected = trimIndentation`\
const _jsxFileName = "";function MyComponent() {
"use strict";const _jsxFileName = "";function MyComponent() {
return api.preact.h('p', {__self: this, __source: {fileName: _jsxFileName, lineNumber: 2}}, "Hello world." );
}
`;
@ -112,7 +112,7 @@ describe("JSX building", () => {
}
`;
const expected = trimIndentation`\
const _jsxFileName = "";function MyComponent() {
"use strict";const _jsxFileName = "";function MyComponent() {
return api.preact.h(api.preact.Fragment, null
, api.preact.h('p', {__self: this, __source: {fileName: _jsxFileName, lineNumber: 3}}, "Hi")
, api.preact.h('p', {__self: this, __source: {fileName: _jsxFileName, lineNumber: 4}}, "there")
@ -121,4 +121,28 @@ describe("JSX building", () => {
`;
expect(buildJsx(script).code).toStrictEqual(expected);
});
it("rewrites export", () => {
const script = trimIndentation`\
const { defineWidget } = api.preact;
export default defineWidget({
parent: "right-pane",
render() {
return <></>;
}
});
`;
const expected = trimIndentation`\
"use strict";Object.defineProperty(exports, "__esModule", {value: true});const { defineWidget } = api.preact;
module.exports = defineWidget({
parent: "right-pane",
render() {
return api.preact.h(api.preact.Fragment, null);
}
});
`;
expect(buildJsx(script).code).toStrictEqual(expected);
});
});

View File

@ -220,11 +220,17 @@ return module.exports;
export function buildJsx(contentRaw: string | Buffer) {
const content = Buffer.isBuffer(contentRaw) ? contentRaw.toString("utf-8") : contentRaw;
return transform(content, {
transforms: ["jsx"],
const output = transform(content, {
transforms: ["jsx", "imports"],
jsxPragma: "api.preact.h",
jsxFragmentPragma: "api.preact.Fragment",
});
output.code = output.code.replaceAll(
/\bexports\s*\.\s*default\s*=\s*/g,
'module.exports = '
);
return output;
}
function sanitizeVariableName(str: string) {