Insert the content of other files, such as code samples, command output or parts of other docs, into your Markdown files, and keep it up to date when those files change.
Mark where the content goes with an HTML comment:
<!--- @@inject: src/example.ts --->Docs such as README.md often repeat code samples, CLI help output or parts of other docs. Copied by hand, they drift out of date. inject-markdown copies them for you, so the source file stays the single source of truth.
-
Install it as a dev dependency (or skip this and use
npx):npm install --save-dev inject-markdown
-
Add a directive where the content should go:
# My Project ## Example <!--- @@inject: code.ts --->
-
Run it on the Markdown file:
npx inject-markdown README.md
The file now contains the content of code.ts, followed by an end marker:
# My Project
## Example
<!--- @@inject: code.ts --->
```ts
export function sayHello(name: string): string {
return `Hello ${name}`;
}
```
<!--- @@inject-end: code.ts --->Run it again after code.ts changes, and the section between the two markers is refreshed.
To keep it in one place, add a script to package.json:
{
"scripts": {
"build:docs": "inject-markdown README.md"
}
}- Directives are HTML comments, so they don't show up when the Markdown is rendered.
- The tool writes content after each directive and closes it with an
@@inject-endmarker. On every run, everything between the directive and its end marker is replaced. Edit the source file, not the injected text. - How content is injected depends on the file type:
.mdfiles are injected as Markdown,.csv/.tsvfiles as a table, and everything else as a fenced code block. The directives and options below override this. - Paths are relative to the Markdown file that contains the directive. A reference can also be an
http(s)URL; GitHubblobURLs are fetched as raw content. - Local references must stay inside the injection root — the directory set by
--cwd, by default the current directory. See Injection root for why, and for--allow-outside-root. - Only
.mdfiles are processed. Pass files or glob patterns:inject-markdown README.md "docs/**/*.md". - Unchanged files are not rewritten.
Commonly used flags:
| Flag | Effect |
|---|---|
--dry-run |
Process the files and report, but don't write anything. |
--clean |
Remove injected content. The directives stay, so the next run restores it. |
--output-dir |
Write the results to another directory instead of in place. |
--verbose |
Show more detail about each file. |
See CLI options for the full list.
--dry-run exits successfully even when content is out of date. To fail a CI job when docs are stale, regenerate them and check for changes:
npx inject-markdown README.md
git diff --exit-code| Directive | Effect |
|---|---|
@@inject: <file> |
Inject the file: Markdown as Markdown, CSV/TSV as a table, anything else as code. |
@@inject-code: <file> |
Always inject as a fenced code block, including Markdown and CSV/TSV files. |
@@inject-table: <file> |
Always inject as a table, whatever the file extension. A .json file must hold an array of objects; @@inject: <file>.json still injects it as code. |
@@inject-start: <file> |
Same as @@inject. |
@@inject-end: <file> |
Marks the end of injected content. The tool writes it; you don't normally need to. |
Add options after a # in the file reference, separated by &:
<!--- @@inject: guide.md#heading=Install"e --->| Option | Applies to | Effect |
|---|---|---|
heading=<text> |
Markdown | Inject only the section under this heading. The shorthand #<text> also works. |
L<n>-L<m> |
All | Inject only lines n to m, e.g. #L5-L7. |
lang=<lang> |
Code | Set the code block's language. On a CSV/TSV file, this injects it as code instead of a table. |
code |
Markdown | Inject Markdown as a code block. code=<lang> is the same as lang=<lang>. |
quote |
All | Inject as a block quote. |
markdown |
Tables | Render inline Markdown in cells instead of escaping it. |
html-table |
Tables | Emit an HTML table whose cells can hold full Markdown, including lists and paragraphs. |
header-rows=<n> |
Tables | How many leading rows form the header. Default 1; 0 means no header. |
start-row=<n> |
Tables | First data row to include, counting from 1 after the header rows. |
end-row=<n> |
Tables | Last data row to include. |
num-rows=<n> |
Tables | Maximum number of data rows. Default 10000. |
rebase-links=false |
Markdown, Tables | Keep relative links as written. By default they're rewritten to resolve from the host file. See Relative links. |
values=<name:val,…> |
All | Values for {@ name @} placeholders. See Template variables. |
value=<name:val> |
All | One placeholder value; commas and colons after the first : are part of the value. |
values-file=<path> |
All | JSON files of placeholder values, comma-separated, each under its file name: values.json gives {@ values.version @}. See Values files. |
values-file=<:path> |
All | Put a file's values at the top level: :values.json gives {@ version @}. |
values-file=<prefix:path> |
All | Put a file's values under your own prefix: pkg:values.json gives {@ pkg.version @}. See Prefixes. |
value-alias=<new:target,…> |
All | Resolve one placeholder name as another. |
vars |
All | Opt in with no values of its own, to use values from the command line and allowed environment variables. |
Each example shows the directive and what the tool writes after it.
<!--- @@inject: example.md --->
# Example
This is an example bit of markdown.
- first
- second
- third
<!--- @@inject-end: example.md --->Relative links in an injected file are rewritten to resolve from the file they're injected into. Here parts/links.md, one directory down, links to ../example.md. Injected into a file next to example.md, that link becomes example.md:
<!--- @@inject: parts/links.md --->
Read the [relative links guide](../docs/guide/relative-links.md)
or the [example](example.md).
<!--- @@inject-end: parts/links.md --->Use #rebase-links=false or --no-rebase-links to keep links as written. See Relative links for what is and isn't rewritten.
The section runs from the heading up to the next heading of the same or higher level.
<!--- @@inject: sections.md#heading=Install --->
## Install
```sh
npm install --save-dev inject-markdown
```
<!--- @@inject-end: sections.md#heading=Install --->Non-Markdown files become a code block. The language is taken from the file extension; use lang= to override it.
<!--- @@inject-code: sample.json#lang=jsonc --->
```jsonc
{
"name": "Sample"
}
```
<!--- @@inject-end: sample.json#lang=jsonc ---><!--- @@inject: code.js#L5-L7 --->
```js
export function sayGoodbye(name) {
return `Goodbye ${name}`;
}
```
<!--- @@inject-end: code.js#L5-L7 ---><!--- @@inject-code: example.md --->
```markdown
# Example
This is an example bit of markdown.
- first
- second
- third
```
<!--- @@inject-end: example.md ---><!--- @@inject: example.md#L5-L7"e --->
> - first
> - second
> - third
<!--- @@inject-end: example.md#L5-L7"e --->On GitHub, select the lines, choose Copy permalink, and use the URL as the file reference.
<!--- @@inject: https://github.com/streetsidesoftware/inject-markdown/blob/bbb2c709c/src/FileSystemAdapter/fsa.ts#L26-L29 --->
```ts
async function fetchUrl(url: URL): Promise<string> {
const response = await fetch(mapUrl(url));
return await response.text();
}
```
<!--- @@inject-end: https://github.com/streetsidesoftware/inject-markdown/blob/bbb2c709c/src/FileSystemAdapter/fsa.ts#L26-L29 --->All columns are included. Use @@inject-code or #lang=csv to inject the file as code instead. See Tables for the detailed rules.
<!--- @@inject: sample.csv --->
| name | role |
| ------------ | ------------- |
| Ada Lovelace | Mathematician |
| Grace Hopper | Programmer |
<!--- @@inject-end: sample.csv --->header-rows=<n> makes the first n rows the header:
- With more than one, each column's header rows are joined with
<br />, skipping blank cells. With#html-tablethey stay separate header rows. header-rows=0means every row is data. A pipe table then shows column numbers (1,2, …) as its header, and an#html-tablehas no header.#header-rowswith no value meansheader-rows=1.
<!--- @@inject: sample-header-rows.csv#header-rows=2 --->
| Date | Name<br />First | Name<br />Last |
| ---------- | --------------- | -------------- |
| 1815-12-10 | Ada | Lovelace |
| 1906-12-09 | Grace | Hopper |
<!--- @@inject-end: sample-header-rows.csv#header-rows=2 --->Renders as:
| Date | Name First |
Name Last |
|---|---|---|
| 1815-12-10 | Ada | Lovelace |
| 1906-12-09 | Grace | Hopper |
start-row, end-row and num-rows choose which data rows are injected:
- Rows are numbered from 1, starting after the header rows.
num-rowsdefaults to10000, so a larger file is cut off unless you raise it.- A window past the end of the data gives a table with only its header.
- A value that isn't a whole number, or
start-row=0, is an error.
<!--- @@inject: sample-rows.csv#start-row=2&num-rows=2 --->
| n | planet |
| --- | ------ |
| 2 | Venus |
| 3 | Earth |
<!--- @@inject-end: sample-rows.csv#start-row=2&num-rows=2 --->@@inject-table: also accepts a .json file holding an array of objects. Each object is a row, and its keys are the columns. @@inject: on a .json file still injects a code block.
<!--- @@inject-table: sample-table.json --->
| name | born | fields | rank |
| ------------ | ---- | ---------------------------- | ------------ |
| Ada Lovelace | 1815 | \["mathematics","computing"] | |
| Grace Hopper | 1906 | | Rear Admiral |
<!--- @@inject-end: sample-table.json --->Renders as:
| name | born | fields | rank |
|---|---|---|---|
| Ada Lovelace | 1815 | ["mathematics","computing"] | |
| Grace Hopper | 1906 | Rear Admiral |
- The columns are every key found in the rows being shown, in the order they first appear. If no rows are shown, they're every key in the file. A missing key is an empty cell.
- Numbers and booleans are shown as text, and
nullis an empty cell. - A nested object or array is shown as compact JSON. With
#markdownit's a code span, and with#html-tableit's a formattedjsoncode block. start-row,end-rowandnum-rowswork as for CSV. A line range (#L1-L10) is an error on a JSON source.- The keys are the one header row:
header-rows=0hides it, and a larger value is an error. - The file must be a non-empty array of objects; anything else is an error.
By default, Markdown in a cell is escaped and shown literally. Add #markdown to render inline Markdown (emphasis, code, links, images, strikethrough, inline HTML) in every cell, including the header.
- Block syntax such as
# Titleor- itemstays literal, because a table cell can't hold blocks. - A
|in the CSV is escaped for you; a newline inside a quoted field becomes<br />. - Raw HTML is passed through, so only use
#markdownon CSV files you trust as much as the Markdown around them.
<!--- @@inject: sample-markdown.csv#markdown --->
| option | description |
| ------------ | ------------------------------------------------ |
| `#markdown` | **Bold**, [links](https://github.com) and `a\|b` |
| - not a list | Stays literal<br />and a newline is a line break |
<!--- @@inject-end: sample-markdown.csv#markdown --->Renders as:
| option | description |
|---|---|
#markdown |
Bold, links and a|b |
| - not a list | Stays literal and a newline is a line break |
When cells need lists or paragraphs, use #html-table. It writes an HTML <table> instead of a pipe table, and each cell can hold full Markdown. It implies #markdown.
This relies on a CommonMark rule: a blank line after an HTML tag ends the HTML block, so the cell's content is parsed as Markdown. GitHub and other CommonMark renderers support this; others may show the Markdown as plain text.
<!--- @@inject: sample-html-table.csv#html-table --->
<table>
<thead>
<tr>
<th>option</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
`#html-table`
</td>
<td>
Cells can hold **block** Markdown:
- lists
- several paragraphs
</td>
</tr>
<tr>
<td>plain</td>
<td>Plain cells stay on one line</td>
</tr>
</tbody>
</table>
<!--- @@inject-end: sample-html-table.csv#html-table --->Renders as:
| option | description |
|---|---|
|
|
Cells can hold block Markdown:
|
| plain | Plain cells stay on one line |
Injected content can contain {@ name @} placeholders. The directive supplies the values, so the same snippet can be reused with different values. Given a values-example.md containing npm install my-package@{@ version @}:
<!--- @@inject-code: values-example.md#values=version:1.2.3 --->
```markdown
npm install my-package@1.2.3
```
<!--- @@inject-end: values-example.md#values=version:1.2.3 --->Placeholders are only replaced when the directive has values=, value=, values-file=, value-alias= or vars. Values can also come from JSON files and the command line (--value, --values-file, --value-alias, --allow-env, --strict-vars). See Template variables for the full rules.
inject-markdown can also be called from code. Types are included.
import { injectFile } from 'inject-markdown';
const result = await injectFile('README.md', { cwd: 'samples' });
for (const error of result.errors) {
console.error(`README.md:${error.line}: ${error.message}`);
}injectFilewrites the file back only if it changed and had no errors.- It never prints. It returns:
updated: the content changed.written: the file was written.errorsandwarnings: each has amessage, and the directive'slineandcolumn.
- To process several files, call it once for each.
import { injectMarkdown } from 'inject-markdown';
const result = await injectMarkdown({
file: 'samples/README.md',
content: markdown
});- A document is the Markdown
contentand thefileit belongs to. Relative@@injectpaths resolve fromfile. - Nothing is read from
file, and nothing is written. - It returns the injected
document, plusupdated,errorsandwarnings.
removeDirectives removes the @@inject directives and end markers from Markdown. Everything else stays exactly as written, including the injected content. This is useful for a copy that is published rather than maintained.
import { injectMarkdown, removeDirectives } from 'inject-markdown';
const result = await injectMarkdown({
file: 'docs/guide.md',
content: markdown
});
const published = removeDirectives(result.document.content);injectFile and injectMarkdown take the same options:
cwd: the injection root. Relative paths resolve against it, and local references must stay inside it. Defaults to the current directory.allowOutsideRoot: directories outsidecwdthat local references may resolve into.rebaseLinks: rebase relative links in injected Markdown. Defaults totrue.injectOnly: only rewrite the injected sections. Defaults totrue.clean: remove the injected content, keeping the directives.valueDeclarations: placeholder values, as a list. A later entry overrides an earlier one, and a directive's own values override all of them.allowEnv: environment variables a directive may use.strictVars: treat an unresolved placeholder as an error.
For example, valueDeclarations takes the place of --value, --values-file and --value-alias:
await injectFile('README.md', {
valueDeclarations: [
{
// The file's values, under `package`: {@ package.version @}
kind: 'values-file',
path: 'package.json',
prefix: 'package'
},
{
kind: 'value',
name: 'channel',
value: 'beta'
},
{
kind: 'alias',
name: 'version',
target: 'package.version'
}
]
});A values file's prefix is a dotted name for its values, or '' to put its keys at the top level.
- Errors in the Markdown are returned in
errors, never thrown. - Invalid options throw an
OptionError. This includes a values file that can't be read. - A file that can't be read throws the read error.
- Template variables — placeholders, values files, aliases, CLI values and how they combine.
- Injection root — which local files a directive may read, and
--allow-outside-root.
Help fits the width of your terminal. To use a different width, set the COLUMNS environment variable:
COLUMNS=60 inject-markdown --helpinject-markdown --help
Usage: inject-markdown [options] <files...>
Inject file content into markdown files.
Arguments:
files Files to scan for injected content.
Options:
--no-must-find-files No error if files are not found.
--output-dir <dir> Output Directory
--cwd <dir> Current Directory
--allow-outside-root <dir> Allow local @@inject references to
resolve into <dir>, outside the
injection root (cwd). Repeatable.
--value <name=val> Set a run-wide {@ name @} placeholder
value. Repeatable; the last --value,
--values-file or --value-alias defining
a name overrides earlier ones. A
directive's own values override all of
them.
--values-file <[prefix:]path> Add a run-wide JSON file of {@ name @}
placeholder values, resolved relative
to --cwd. Repeatable; ordered with
--value.
--allow-env <name> Allow a directive to reference the OS
environment variable <name> via {@
env.name @}. Repeatable.
--value-alias <new=target> Resolve the {@ new @} placeholder as if
it were {@ target @}. Repeatable;
ordered with --value and --values-file.
--strict-vars Treat an unresolved {@ name @}
placeholder as a directive error.
--no-rebase-links Keep relative links in injected
Markdown as written instead of rebasing
them.
--no-directives Remove the @@inject directives from
files written to --output-dir.
--clean Remove the injected content.
--no-inject-only Update the whole file.
--verbose Verbose output.
--silent Only output errors.
--no-stop-on-errors Do not stop if an error occurs.
--write-on-error write the file even if an injection
error occurs.
--color Force color.
--no-color Do not use color.
--no-summary Do not show the summary
--dry-run Process the files, but do not write.
-V, --version output the version number
-h, --help display help for command
Brought to you by
Street Side Software