我正在尝试设置一个插件来更改开发服务器和生产版本上VuePress markdown文件的内容。根据文档,我应该能够使用_content
_strippedContent
和extendPageData
以下代码是我在插件中设置的。
module.exports = (options = {}, context) => ({
extendPageData($page) {
const {
_filePath, // file's absolute path
_computed, // access the client global computed mixins at build time, e.g _computed.$localePath.
_content, // file's raw content string
_strippedContent, // file's content string without frontmatter
key, // page's unique hash key
frontmatter, // page's frontmatter object
regularPath, // current page's default link (follow the file hierarchy)
path, // current page's real link (use regularPath when permalink does not exist)
} = $page
$page._content = "replaced"
$page._strippedContent = "replaced"
}
})
我能说的最好的是,该代码应该在更新$page._content
时起作用,但是它并没有显示testing
而是原始内容。
我知道我会尽可能从文件中console.log
进入这段代码,它会显示在控制台中。
我担心$page._content
是不可变的,想知道在dev
或build
期间是否有一种方法可以进行这种内容交换
答案 0 :(得分:2)
在编译Markdown之后以及渲染Vue组件期间,将使用这些页面对象中的信息。内容更多,供您参考,对其进行修改不会影响您。
这也把我绊倒了。
所有markdown文件都进行了信息处理,但是实际的编译是通过webpack进行的。一般流程为:
.md
-> markdown-loader
-> vue-loader
-> ...
我的建议和所做的工作是创建一个自定义Webpack加载器,以在内容通过VuePress markdown加载器之前对其进行修改。我使用这种方法通过Nunjucks来运行我的markdown文件来模板化markdown之前的模板。在找出正确的方法之后,执行此操作非常容易:)这是一种可行的方法:
config.js:
chainWebpack: config => {
config.module
.rule('md')
.test(/\.md$/)
.use(path.resolve(__dirname, './nunjucks'))
.loader(path.resolve(__dirname, './nunjucks'))
.end()
},
然后一个简单的加载器可以看起来像这样(删节的):
module.exports = function(source) {
const rendered = nunjucks.renderString(source, config)
return rendered
}
答案 1 :(得分:0)
我认为您应该使用extendMarkdown
https://v1.vuepress.vuejs.org/config/#markdown-extendmarkdown。
尝试这样
// index.js
module.exports = () => ({
name: 'vuepress-plugin-foo-bar',
extendMarkdown: md => {
const render = md.render;
md.render = (...args) => {
// original content
const html = render.call(md, ...args);
return 'new content';
};
},
});
答案 2 :(得分:0)
您可以修改 .vuepress / config.js 。例如,如果要在所有文件降价中将“ ---我的文本---”替换为“我的文本
”(例如大写),则必须将下一个代码添加到 .vuepress / config.js ,进入chainWebpack部分,在这里我使用正则表达式:
// File: .vuepress/config.js
module.exports = {
...,
chainWebpack: config => {
// Each loader in the chain applies transformations to the processed resource:
config.module
.rule('md')
.test(/\.md$/)
.use("string-replace-loader")
.loader("string-replace-loader")
.options({
multiple: [{
search: '---(.*?)---',
replace: (match, p1, offset, string, groups) => `<div><p class="myclass">${p1.toUpperCase()}</p></div>`,
flags: 'ig'
},
{
search: ' ... ',
replace: (match, p1, p2, ..., pn, offset, string) => ` ... `,
flags: 'ig'
}
],
}, )
.end()
},
};