diff --git a/__tests__/e2e/markdown-extensions/bar.md b/__tests__/e2e/markdown-extensions/bar.md new file mode 100644 index 00000000..e1c4eb24 --- /dev/null +++ b/__tests__/e2e/markdown-extensions/bar.md @@ -0,0 +1 @@ +# Bar diff --git a/__tests__/e2e/markdown-extensions/index.md b/__tests__/e2e/markdown-extensions/index.md index 5bb4325a..348bdca9 100644 --- a/__tests__/e2e/markdown-extensions/index.md +++ b/__tests__/e2e/markdown-extensions/index.md @@ -175,4 +175,8 @@ export default config ## Markdown File Inclusion - \ No newline at end of file + + +## Markdown At File Inclusion + + diff --git a/__tests__/e2e/markdown-extensions/markdown-extensions.test.ts b/__tests__/e2e/markdown-extensions/markdown-extensions.test.ts index 24b38e01..b844647b 100644 --- a/__tests__/e2e/markdown-extensions/markdown-extensions.test.ts +++ b/__tests__/e2e/markdown-extensions/markdown-extensions.test.ts @@ -63,7 +63,7 @@ describe('Table of Contents', () => { test('render toc', async () => { const items = page.locator('#table-of-contents + nav ul li') const count = await items.count() - expect(count).toBe(23) + expect(count).toBe(24) }) }) @@ -229,4 +229,8 @@ describe('Markdown File Inclusion', () => { const h1 = page.locator('#markdown-file-inclusion + h1') expect(await h1.getAttribute('id')).toBe('foo') }) + test('render markdown using @', async () => { + const h1 = page.locator('#markdown-at-file-inclusion + h1') + expect(await h1.getAttribute('id')).toBe('bar') + }) }) diff --git a/docs/guide/markdown.md b/docs/guide/markdown.md index 392f4008..a3466deb 100644 --- a/docs/guide/markdown.md +++ b/docs/guide/markdown.md @@ -691,7 +691,13 @@ You can also [import snippets](#import-code-snippets) in code groups: ## Markdown File Inclusion -You can include a markdown file in another markdown file like this: +You can include a markdown file in another markdown file. + +::: tip +You can also prefix the markdown path with `@`, it will act as the source root. By default it's the VitePress project root, unless `srcDir` is configured. +::: + +For example, you can include a relative markdown file using this: **Input** diff --git a/src/node/markdownToVue.ts b/src/node/markdownToVue.ts index c38ec541..84c6fe70 100644 --- a/src/node/markdownToVue.ts +++ b/src/node/markdownToVue.ts @@ -87,9 +87,15 @@ export async function createMarkdownToVueRenderFn( // resolve includes let includes: string[] = [] src = src.replace(includesRE, (m, m1) => { + if (!m1.length) return m + + const atPresent = m1[0] === '@' try { - const dir = path.dirname(fileOrig) // include paths are strict relative file paths w/o aliases - const includePath = path.join(dir, m1) + const dir = atPresent ? srcDir : path.dirname(fileOrig) + const includePath = path.join( + dir, + atPresent ? m1.slice(m1.length > 1 && m1[1] === '/' ? 2 : 1) : m1 + ) const content = fs.readFileSync(includePath, 'utf-8') includes.push(slash(includePath)) return content