nginx访问md文件在vue项目展示

266 阅读1分钟

如果把md文件放到服务器上面,浏览器直接访问会直接下载,nginx配置md文件访问是md

location /help {
                index index.html index.htm index.md;
                try_files $uri $uri/ /help/index.md;
        }

        location ~ ^/help/(.*)\.md$ {
                add_header Content-Type text/plain;
                alias /usr/share/nginx/html/help/$1.md;
        }
		location /help/images {
			alias /usr/share/nginx/html/help/images;
		}

/help/images是配置图片路径

vue项目安装 npm install markdown-it --save

使用正则将md文件里面的图片格式和img标签进行路径前缀拼接,以及图片空白进行%20转换

组件代码

<template>
  <div>
    <div class="md" v-html="renderedMarkdown"></div>
  </div>
</template>

<script lang="ts" setup>
import MarkdownIt from "markdown-it";
import axios from "axios";
import { useRoute } from "vue-router";
import func from "vue-temp/vue-editor-bridge";

const route = useRoute();
const { url, renderedMarkdown } = toRefs(
  reactive({
    url: route.query.url,
    renderedMarkdown: "",
  })
);

onMounted(() => {
  renderMarkdown();
});

async function renderMarkdown() {
  const md = new MarkdownIt("default", {
    html: true,
    linkify: true,
    typographer: true,
  });
  let res = await axios.get(process.env.VUE_APP_HELP + url.value);
  // 获取Markdown文本中的所有img元素
  let markdown = processMD(res.data);

  // 将转换后的Markdown文本渲染为HTML字符串
  renderedMarkdown.value = md.render(markdown);
}
/**
 * @description: 将md的图片中的空格和img、![]转换为img标签
 * @param {*} markdowm 需要转换的str
 * @return {*} html 转换后的html
 * @author: lihk
 */
function processMD(markdown) {
  function encodeSpaces(str) {
    return str.replace(/\s/g, "%20");
  }
  const prefix = "路径";
  const imgRegex = /(!\[.*?\]\()(.*?)(\))/g;
  const newMarkdown = markdown.replace(imgRegex, (match, p1, p2, p3) => {
    let img = encodeSpaces(p2);
    return p1 + prefix + img + p3;
  });
  const html = newMarkdown.replace(
    /<img(.*?)src="(.*?)".*?>/g,
    (match, attrs, p1) => {
      let img = encodeSpaces(p1);
      return `<img ${attrs} src="${prefix + img}">`;
    }
  );
  console.log('html', newMarkdown)
  return html
}
</script>
<style lang="scss" scoped>
.md {
  padding: 20px;
  width: calc(100vw - 400px);
}
:deep(img) {
  max-width: 100% !important;
}
:deep(h4:nth-child(1)) {
  font-size: 20px;
  padding-bottom: 26px;
  border-bottom: 1px solid #e5e5e5;
}
</style>