Re-use Next.js' JSX transform in external Node.js script
Unanswered
Kurilian Bobtail posted this in #help-forum
Kurilian BobtailOP
I have a Next.js project that uses
Due to
I already know that i can re-use
Can i re-use any JSX transformer from the
export
that i want to add an RSS feed to.Due to
export
, using API routes is not an option and instead i want to add a simple script to npm run build
that creates the RSS/XML file.I already know that i can re-use
react-dom/server
to render React to a string, which already makes templating the feed easy, but i'm missing JSX support.Can i re-use any JSX transformer from the
next
or other required package (babel? swc?) without explicitly installing any new dependencies myself?2 Replies
Kurilian BobtailOP
import * as ts from "typescript";
const tsxCode = await fs.readFile("./Test.tsx", "utf-8");
const jsCode = ts.transpileModule(tsxCode, {
compilerOptions: {
jsx: ts.JsxEmit.Preserve,
},
}).outputText;
this is already getting pretty close but the output is still messy and now i need to figure out how to import a module from a string
Kurilian BobtailOP
this works. it's not super elegant though, especially the use of
globalThis
:import ReactDOMServer from "react-dom/server";
import fs from "node:fs";
import ts from "typescript";
import react from "react";
const { outputText: jsCode } = ts.transpileModule(
fs.readFileSync("./Test.tsx", "utf-8"),
{
compilerOptions: {
jsx: ts.JsxEmit.React,
module: ts.ModuleKind.ES2022,
},
}
);
globalThis.React = react;
const module = await import(
`data:text/javascript;base64,${Buffer.from(jsCode).toString("base64")}`
);
const s = ReactDOMServer.renderToString(module.Foo());
console.log(s);