Markdown AST Injection Utility
md-node-inject is a utility for programmatically injecting Markdown Abstract Syntax Tree (AST) nodes into specific sections of another Markdown AST. Currently at stable version 2.0.0, this package is designed to work with parsed Markdown content, allowing for precise content integration without string manipulation. It differentiates itself by operating directly on ASTs, which prevents common issues associated with regex-based text replacement and ensures syntactically correct output. The library is ESM-only and requires Node.js v14 or higher for execution. It's often used in conjunction with other AST parsing and serialization libraries like `markdown-to-ast` and `ast-to-markdown` to form a complete Markdown processing pipeline.
Common errors
-
ERR_REQUIRE_ESM
cause Attempting to `require()` the `md-node-inject` package, which is an ESM-only module, in a CommonJS environment.fixMigrate your module loading to ES module syntax: change `const inject = require('md-node-inject');` to `import inject from 'md-node-inject';`. Also, ensure your `package.json` includes `"type": "module"` if running in Node.js. -
ReferenceError: require is not defined
cause Using the `require()` function within an ES module file (e.g., a `.mjs` file or a file in a `"type": "module"` project) when `md-node-inject` is also an ES module.fixReplace all `require()` calls, particularly for `md-node-inject`, with corresponding `import` statements. `require` is not available in native ES modules.
Warnings
- breaking md-node-inject is an ESM-only package. It cannot be loaded using CommonJS `require()` and requires ES module syntax.
- gotcha The package requires Node.js version 14 or higher due to its exclusive reliance on ES modules and modern JavaScript features.
Install
-
npm install md-node-inject -
yarn add md-node-inject -
pnpm add md-node-inject
Imports
- inject
const inject = require('md-node-inject');import inject from 'md-node-inject';
Quickstart
import ast from 'markdown-to-ast'; import toMarkdown from 'ast-to-markdown'; import inject from 'md-node-inject'; const mdContent = ` # Sample Description # API # License MIT `; const mdApiContent = ` ## method() Method description `; const mdContentAst = ast.parse(mdContent); const mdApiContentAst = ast.parse(mdApiContent); const injectionSection = 'API'; const mergedContentAst = inject(injectionSection, mdContentAst, mdApiContentAst); const mergedContent = toMarkdown(mergedContentAst); console.log(mergedContent);