feat(build): support relative path for code snippet (#1894)

Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
pull/1844/head
CHOYSEN 1 year ago committed by GitHub
parent 80e734d677
commit 90478b36cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -566,7 +566,12 @@ It also supports [line highlighting](#line-highlighting-in-code-blocks):
<<< @/snippets/snippet.js{2}
::: tip
The value of `@` corresponds to the source root. By default it's the VitePress project root, unless `srcDir` is configured.
The value of `@` corresponds to the source root. By default it's the VitePress project root, unless `srcDir` is configured. Alternatively, you can also import from relative paths:
```md
<<< ../snippets/snippet.js
```
:::
You can also use a [VS Code region](https://code.visualstudio.com/docs/editor/codebasics#_folding) to only include the corresponding part of the code file. You can provide a custom region name after a `#` following the filepath:

@ -2,6 +2,7 @@ import fs from 'fs-extra'
import path from 'path'
import type MarkdownIt from 'markdown-it'
import type { RuleBlock } from 'markdown-it/lib/parser_block'
import type { MarkdownEnv } from '../env'
export function dedent(text: string): string {
const lines = text.split('\n')
@ -107,7 +108,7 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
.trim()
const [
filename = '',
filepath = '',
extension = '',
region = '',
lines = '',
@ -115,7 +116,7 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
rawTitle = ''
] = (rawPathRegexp.exec(rawPath) || []).slice(1)
const title = rawTitle || filename.split('/').pop() || ''
const title = rawTitle || filepath.split('/').pop() || ''
state.line = startLine + 1
@ -124,8 +125,12 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
title ? `[${title}]` : ''
}`
const resolvedPath = path.resolve(
path.dirname((state.env as MarkdownEnv).path),
filepath
)
// @ts-ignore
token.src = path.resolve(filename) + region
token.src = [resolvedPath, region.slice(1)]
token.markup = '```'
token.map = [startLine, startLine + 1]
@ -138,8 +143,7 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
const [tokens, idx, , { loader }] = args
const token = tokens[idx]
// @ts-ignore
const tokenSrc = token.src
const [src, regionName] = tokenSrc ? tokenSrc.split('#') : ['']
const [src, regionName] = token.src ?? []
if (src) {
if (loader) {

Loading…
Cancel
Save