Custom Polyfill Transforms
This recipe shows how to use polyfillTransform to customize the polyfill code generated by jspicl.
What are Polyfills?
When you use JavaScript methods that don't have direct Lua equivalents (like array.map(), array.filter(), etc.), jspicl generates polyfill functions prefixed with _ (e.g., _map(), _filter()). These are included in your cartridge automatically.
Basic Usage
The polyfillTransform function receives a record where keys are polyfill names and values are their implementations. It must return a string:
// jspicl.config.ts
import type {Config} from "@jspicl/cli/types";
const config: Config = {
polyfillTransform: (polyfills) => {
// Return the code unchanged, or modify it
return Object.values(polyfills).join("\n");
}
// ...
};
export default config;
Example: Adding a Header Comment
const config: Config = {
polyfillTransform: (polyfills) => {
return `-- polyfills generated by jspicl
${Object.values(polyfills).join("\n")}`;
}
// ...
};
Example: Minifying Polyfills
Remove extra whitespace to save tokens:
const config: Config = {
polyfillTransform: (polyfills) => {
return Object.values(polyfills)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.join("\n");
}
// ...
};
Example: Replacing a Polyfill Implementation
If you have a more token-efficient implementation of a polyfill:
const config: Config = {
polyfillTransform: (polyfills) => {
// Replace the default _map implementation with a custom one
if ("_map" in polyfills) {
polyfills._map = `...`;
}
return Object.values(polyfills).join("\n");
}
// ...
};
When to Use This
- Adding comments or markers to generated code
- Minifying polyfills to save tokens
- Replacing polyfill implementations with optimized versions
- Wrapping polyfills in a specific structure
- Debugging: logging which polyfills are being used