A simple cli command to materialize the response of a typescript async function during build time.
import { readFile } from "fs/promises";
/**
* @materialized
*/
async function getVersion() {
// return anything that survives JSON.stringify()
const pkg = await readFile("./package.json");
const parsed = JSON.parse(pkg.toString());
return parsed.version;
}
npx materialize-ts-function
/**
* @materialized
*/
async function getVersion() {
/* __materialized__ */
return "1.0.0";
}
Use any boolean returning expression with @if
annotation
/**
* @materialized
* @if process.env.DEBUG !== undefined
*/
async function someComplexLogic() {
// add business logic here
}
We scan the codebase for all files containing functions with the @materialized
annotation and temporarily add a simple statement to the end of the file to make it executable with ts-node
.
Then we capture the output and replace the annotated functions body with the serialized response from the ts-node execution.
// Temporary statements to execute the function
import { materialize } from "materialize-ts-function";
materialize(
someComplexLogic, // <-- @materialized function
process.env.DEBUG !== undefined // <-- @if annotation literal
)
.then(console.log)
.catch(console.error);
To debug one can add the same statement to the file and execute if with
ts-node ./src/original/file/location.ts
... happy coding :)