From a47257e2aafe66b39a2528c20a60ee365ad20bf0 Mon Sep 17 00:00:00 2001 From: Shigma <1700011071@pku.edu.cn> Date: Tue, 26 Feb 2019 21:37:36 +0800 Subject: [PATCH] Update snippet.js --- packages/@vuepress/markdown/lib/snippet.js | 25 +++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/@vuepress/markdown/lib/snippet.js b/packages/@vuepress/markdown/lib/snippet.js index 895e7b2d5f..b0b88f18f2 100644 --- a/packages/@vuepress/markdown/lib/snippet.js +++ b/packages/@vuepress/markdown/lib/snippet.js @@ -1,7 +1,27 @@ -const { fs } = require('@vuepress/shared-utils') +const { fs, path } = require('@vuepress/shared-utils') module.exports = function snippet (md, options = {}) { + const fence = md.renderer.rules.fence const root = options.root || process.cwd() + + md.renderer.rules.fence = (...args) => { + const [tokens, idx, , { loader }] = args + const token = tokens[idx] + const { src } = token + if (src) { + if (loader) { + loader.addDependency(src) + } + if (fs.existsSync(src)) { + token.content = fs.readFileSync(src, 'utf8') + } else { + token.content = 'Not found: ' + src + token.info = '' + } + } + return fence(...args) + } + function parser (state, startLine, endLine, silent) { const CH = '<'.charCodeAt(0) const pos = state.bMarks[startLine] + state.tShift[startLine] @@ -25,14 +45,13 @@ module.exports = function snippet (md, options = {}) { const end = state.skipSpacesBack(max, pos) const rawPath = state.src.slice(start, end).trim().replace(/^@/, root) const filename = rawPath.split(/[{\s]/).shift() - const content = fs.existsSync(filename) ? fs.readFileSync(filename).toString() : 'Not found: ' + filename const meta = rawPath.replace(filename, '') state.line = startLine + 1 const token = state.push('fence', 'code', 0) token.info = filename.split('.').pop() + meta - token.content = content + token.src = path.resolve(filename) token.markup = '```' token.map = [startLine, startLine + 1]