codeImport()

Import code from external files into fenced code blocks.

import { codeImport } from "@unifast/node";

Signature

function codeImport(options?: CodeImportPluginOptions): UnifastPlugin

Parameters

options?

Configuration for code import behavior

PropertyTypeDefaultDescription
rootDirstringRoot directory for resolving file paths. When omitted, paths are resolved relative to the current working directory.

Usage

import { compile, codeImport } from "@unifast/node";

const md = `
\`\`\`ts file="./src/example.ts"
\`\`\`
`;

const result = compile(md, {
  plugins: [
    codeImport({
      rootDir: "/path/to/project",
    }),
  ],
});

console.log(result.output);
// The code block is replaced with the contents of ./src/example.ts

Examples

Basic file import

```ts file="./src/utils.ts"
```

The code block content is replaced with the file contents, preserving the language for syntax highlighting.

With rootDir

import { compile, codeImport } from "@unifast/node";

const result = compile(md, {
  plugins: [
    codeImport({ rootDir: "/home/user/project" }),
  ],
});

console.log(result.output);
// File paths are resolved relative to rootDir

Without rootDir

import { compile, codeImport } from "@unifast/node";

const result = compile(md, {
  plugins: [codeImport()],
});

console.log(result.output);
// File paths are resolved relative to the current working directory