comment_templates
Update markdown, TypeScript, and JavaScript files in place using comments as template tags.
Why?
Often, while developing a project, you will want to automatically update sections of content in the file. For example:
- The
versionhas been updated and should be reflected in multiple files. - The API has changed and the autogenerated documentation needs to be updated in the
readme.mdfile.
The solution is to wrap the content you want to replace in a language specific comment block. A build command is then run which injects values into the comment tag while preserving the tags. This means that blocks can be updated multiple times with new data.
API
| import {
commentTemplate,
} from "https://deno.land/x/comment_templates@0.1.0/mod.ts";
import { assertEquals } from "./tests/deps.ts";
const exampleVersion = "2.1.0";
const exampleName = "Comment Template!";
const fileUrl = new URL("tests/fixtures/sample.md", import.meta.url);
const content = await Deno.readTextFile(fileUrl);
// Transform and use the variables in the content.
const transformed = commentTemplate({
content,
variables: { exampleVersion, exampleName },
});
assertEquals(
transformed,
`# <!-- ={exampleName} -->CommentTemplate!<!-- {/exampleName} --><!-- ={exampleVersion|prefix:"@"|code:null} -->\`@2.1.0\`<!-- {/exampleVersion} -->\n`,
);Before: # <!-- ={name} --><!-- {/name} --><!-- ={version|prefix:"@"|code:null} --><!-- {/version} -->After: # <!-- ={name} -->package<!-- {/name} --><!-- ={version} -->`@2.1.0`<!-- {/version} --> |
| content The import {
commentTemplate,
type CommentTemplateProps,
} from "https://deno.land/x/comment_templates@0.0.0/mod.ts";
const props: CommentTemplateProps = {
content: await Deno.readTextFile(
new URL("tests/fixtures/sample.md", import.meta.url),
),
variables: { name: "Deno" },
};
const transformedContent = commentTemplate(props);variables Here is an example of creating variables with both a function and a string. import {
type CommentTemplateProps,
} from "https://deno.land/x/comment_templates@0.0.0/mod.ts";
const props: CommentTemplateProps = {
content: await Deno.readTextFile(
new URL("tests/fixtures/sample.md", import.meta.url),
),
variables: {
simple: "a simple string",
complex: (value) => value ? `${value} is complex` : "seems undefined",
},
};exclude The following example excludes a match based on the provided name. import { CommentTemplateProps } from "https://deno.land/x/comment_templates@0.0.0/mod.ts";
const props: CommentTemplateProps = {
content: "<!-- ={excludedName} --><!-- {/excludedName} -->",
variables: {},
exclude: ({ name }) => name.startsWith("excluded"),
}; |
| The following example extracts the snippets from the provided content. import {
extractTemplateValues,
} from "https://deno.land/x/comment_templates@0.1.0/mod.ts";
const content = await Deno.readTextFile("./mod.d.md");
const variables = extractTemplateValues(content);
// => ReadonlyMap<string, string> |