Skip to content

Build your personal knowledge base with Trilium Notes

feat(script/jsx): support export default syntax

Elian Doran284b66acd271
diff --git a/apps/server/src/services/script.spec.ts b/apps/server/src/services/script.spec.ts
index ec9158b1d8..f7d69688bc 100644
--- a/apps/server/src/services/script.spec.ts
+++ b/apps/server/src/services/script.spec.ts
@@ -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);
+ });
});
diff --git a/apps/server/src/services/script.ts b/apps/server/src/services/script.ts
index b7fff617cc..bf65c448f7 100644
--- a/apps/server/src/services/script.ts
+++ b/apps/server/src/services/script.ts
@@ -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) {