vue项目使用vue-markdown-loader引入加载md文件

1,663 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第10天,点击查看活动详情 >>

vue项目加载md文件两种加载需求,一种是导入本地md文件渲染,一种是加载远程md文件渲染,本地导入用的是 vue-markdown-loader 导入,而远程加载用的是 markdown-it-vue

一、本地导入

1.安装 vue-markdown-loader

yarn add vue-markdown-loader -D

npm i html-loader markdown-loader --save

这里注意了!html-loader的版本号不能太新,不然有可能是要报错的。

2.安装 github-markdown-css、highlight.js

yarn add github-markdown-css  -D
yarn add highlight.js  -D

3.在vue.config.js中配置webpack

chainWebpack: (config) => {
    config.module.rule('md')
        .test(/\.md/)
        .use('vue-loader')
        .loader('vue-loader')
        .end()
        .use('vue-markdown-loader')
        .loader('vue-markdown-loader/lib/markdown-compiler')
        .options({
          raw: true
        }) 
}

4.页面引入样式

// markdown样式
import 'github-markdown-css'
// 代码高亮
import 'highlight.js/styles/github.css'

5.使用

<template>
  <div class="content">
  	<!-- class的值必须包含 markdown-body -->
    <div class="markdown-body" style="width:40%;padding:0 20px">
      <md></md>
   </div>
  </div>
</template>

<script>
import md from './index.md'

export default {
  components :{md}
};
</script>

二、远程加载

  1. 安装markdown-it-vue
npm i markdown-it-vue
  1. 使用
<template>
    <div class="md-content">
        <markdown-it-vue class="md-body" :content="htmlMD"/>
    </div>
</template>
<script>
import axios from 'axios';
import MarkdownItVue from 'markdown-it-vue'
import 'markdown-it-vue/dist/markdown-it-vue.css'
export default {
   data(){
       return {
            htmlMD:""
       }
   },
   components:{
        MarkdownItVue
   },
   created(){
       axios.get("/mdFile/aa.md").then((response) => {
          this.htmlMD = response.data;
            console.log(this.htmlMD)
      });
   }
}
</script>
<style>

</style>

结语

以上就是vue导入.md文件使用vue-markdown-loader解析markdown语法的详细内容,希望对大家有用。