code-fragments is an extremely simple and easy-to-use JS "template" 🤡.
The code-fragments package exposes createFragments
and CodeFragments
to create fragments.
import { createFragments } from 'code-fragments';
const fragments = createFragments();
// or
import { CodeFragments } from 'code-fragments';
const fragments = new CodeFragments();
Just use code fragments as an array, and call fragments.complete
to output the final code.
Accept nested fragments, which will be indented with 2 spaces per depth:
const fragments = new CodeFragments();
fragments.push(
'const fn = () => {',
fragments.fragments('// ...', 'return null;'), // Same as createFragments('// ...', 'return null;')
'};'
);
fragments.push('fn();');
fragments.push(`console.log('fn has been called.');`);
const code = fragments.complete();
/* You got:
const fn = () => {
// ...
return null;
};
fn();
console.log('fn has been called.');
*/
Accept a function to lazy complete dynamic fragments.
const fragments = new CodeFragments<{ name: string }>(); // Specify the context type for your dynamic fragments.
fragments.push('const fn = () => { return null };');
fragments.push('fn();');
fragments.push((context) => `console.log('${context.name} has been called.');`);
const code = fragments.complete({
context: {
name: 'fn',
},
});
/* You got:
const fn = () => { return null };
fn();
console.log('fn has been called.');
*/
Accept a function or a string to customize separator.
const fragments = new CodeFragments<{ name: string }>(); // Specify the context type for your dynamic fragments.
fragments.push('const fn = () => { return null };');
fragments.push('fn();');
fragments.push((context) => `console.log('${context.name} has been called.');`);
const code = fragments.complete({
context: {
name: 'fn',
},
separator: () => `/** CUSTOM_SEPARATOR */`,
});
// You got:
// const fn = () => { return null };/** CUSTOM_SEPARATOR */fn();/** CUSTOM_SEPARATOR */console.log('fn has been called.');
https://www.jsdocs.io/package/code-fragments
Published under MIT.