在 vue/vite 项目中将文件作为字符串加载

rea*_*f0x 3 javascript fetch-api javascript-marked vuejs3 vite

我有一个 vue/vie 项目,在该项目中我试图使用 markdown 将我的 markdown 文件读取到 html 中。

我尝试使用 fetch api 将其作为字符串导入,但只是因为我无法弄清楚如何在 vue 中使用 node.js 代码。

这是 vue 文件:

<script setup>
import { marked } from 'marked'
</script>

<script>
export default {
    data() {
        return {
            query: this.getQueryVariable("q"),
            markdown: ''
        }
    },
    mounted() {
        fetch('../src/markdown/About.md')
            .then(response => response.text())
            .then(text => this.markdown = text)
        document.querySelector('.marked').innerHTML = marked.parse(this.markdown)
    }
}
</script>

<template>
    <div class='marked'>
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)

aba*_*umg 6

使用 Vite,您可以使用后缀和/将资产作为字符串导入?rawasyncawait

const markdownFileContent = (await import(`path/to/markdown/file.md?raw`)).default;
const htmlString = marked.parse(markdownFileContent);
Run Code Online (Sandbox Code Playgroud)