Webpack cannot directly load .md files, but it is common for some blog or article guidance content to be edited and managed through markdown. This requires us to perform some configurations so that webpack can load .md files and display the file contents. to the web page.
1. First write an md loader
Before that, we need to install markdown-it first , create a new md-loader.js file, and edit the code as follows
// md-loader.js
const md = require('markdown-it')()
module.exports = function (source) {
this.cacheable()
// source 是原始文件内容,html 是用 markdown-it 编译后的 html 内容
const html = md.render(source)
const template = (
`<template>
<div class="markdown-body">
${html}
</div>
</template>`
)
return template
}
2. webpack configuration
Add configuration in vue.config.js
const path = require('path') // 引入path模块
module.exports = {
chainWebpack: (config) => {
config.module.rule('markdown').test(/\.md$/)
.use('vue-loader')
.loader('vue-loader')
.end()
.use('md-loader')
.loader(path.resolve(__dirname, './src/loaders/md-loader.js'))
.end()
}
}
3. Loading of .md
Create new md-loader.vue, test.md
<template>
<Test />
</template>
<script>
import Test from './test.md'
export default {
components: {
Test
}
}
</script>
At this point, the .md can be loaded normally and displayed on the web page, but the style here may need some adjustments. You can write it yourself or quote it.
4. Automatically register routes
Every time we add a .md file here, we have to manually modify the code to introduce it, which is a bit troublesome. Then we can set up automatic routing for it. Just traverse all the .md files in a certain folder to generate the corresponding route.
The new directories are as follows:
<!-- md-loader/index.vue -->
<template>
<div>
<router-view></router-view>
</div>
</template>
// router.js
const mdRoutes = []
const md = require.context('md-loader/md', false, /\w+\.(md)$/)
// 遍历 md-loader/md 目录下所有 md 文件, 并生成路由
md.keys().forEach(fileName => {
const reg = /\.\/(.+).md/
const name = fileName.match(reg)[1]
mdRoutes.push({
path: name,
name: name,
component: resolve => require([`md-loader/md/${name}.md`], resolve)
})
})
export const router = [
{
path: '/mdLoader',
name: 'mdLoader',
redirect: '/mdLoader/md1', // 重定向到第一篇文章
component: resolve => require(['md-loader/index.vue'], resolve),
children: mdRoutes,
}
]
Now open https://127.0.0.1:8080/#/mdLoader and jump to https://127.0.0.1:8080/#/mdLoader/md1