Skip to content

Commit

Permalink
feat(build): allow using @ prefix with @include: (#2292)
Browse files Browse the repository at this point in the history
  • Loading branch information
userquin committed Apr 29, 2023
1 parent 67443ce commit a3b38d1
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 5 deletions.
1 change: 1 addition & 0 deletions __tests__/e2e/markdown-extensions/bar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Bar
6 changes: 5 additions & 1 deletion __tests__/e2e/markdown-extensions/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,8 @@ export default config

## Markdown File Inclusion

<!--@include: ./foo.md-->
<!--@include: ./foo.md-->

## Markdown At File Inclusion

<!--@include: @/markdown-extensions/bar.md-->
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})

Expand Down Expand Up @@ -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')
})
})
8 changes: 7 additions & 1 deletion docs/guide/markdown.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**

Expand Down
10 changes: 8 additions & 2 deletions src/node/markdownToVue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit a3b38d1

Please sign in to comment.