hydrate-text
v5.1.0
Published
A small, dependency-free and strongly typed template engine.
Downloads
24
Maintainers
Readme
hydrate-text
A small, dependency-free and strongly typed template engine.
Features
- Light-weight. Less than 1 KiB (actual size depends on imported functions).
- Dependency-free. Only bundled JavaScript files and TypeScript type declarations are included.
- Tree-shakable. Only imported code comes to your bundle.
- Strongly typed with TypeScript. All types are exported alongside with the core functions.
- Flexible interpolation options change. Change variables' markers in each function or use a special function to configure them once for further usage.
Examples
import { hydrateText } from "hydrate-text";
// "Hello, John!"
console.log(
hydrateText("Hello, {username}!", {
username: "John",
}),
);
// "/users/42"
console.log(
hydrateText(
"/users/:id",
{ id: 42 },
{
prefix: ":",
suffix: "",
},
),
);
TypeScript checks that all the variables defined in the given string are provided.
console.log(
hydrateText(
"Hello, {username}!",
// No errors
{
username: "John",
},
),
);
console.log(
hydrateText(
"Hello, {username}!",
// Error: `username` is missing
{},
),
);
Interpolation options can be configured via configureHydrateText
function,
that returns hydrateText
function as a result.
import { configureHydrateText } from "hydrate-text";
const hydrateRoute = configureHydrateText({ prefix: ":" });
// "/users/42"
console.log(hydrateRoute("/users/:id", { id: 42 }));
// "/users/42"
console.log(
hydrateRoute(
"/users/(id)",
{ id: 42 },
{
prefix: "(",
suffix: ")",
},
),
);
Check out other correct and incorrect usage examples.
Installation
npm
npm install hydrate-text
Yarn
yarn add hydrate-text
API (simplified)
type ValueType = string | boolean | number | bigint;
interface InterpolationOptions {
prefix: string;
suffix: string;
}
function hydrateText(
text: string,
variables?: Record<string, ValueType>,
interpolationOptions?: InterpolationOptions,
) {}
function configureHydrateText(
interpolationOptions: InterpolationOptions,
) => typeof hydrateText;
Check out the "Types" section in the source file for more information.
Known issues
SyntaxError: Unexpected token 'export'.
The problem appears when running tests using Jest. That's because of lack of CommonJS support. A solution can be found here. Not supporting CommonJS is intended, since all the industry is moving towards ES modules, and CommonJS will be retired at some point.
Background
Why I wrote "hydrate-text" library