Load file as string in vue/vite project

2.6k Views Asked by At

I have a vue/vie project in which I'm trying to read a markdown file I have into html using marked.

I attempted to use the fetch api to import it as a string, but only because I couldn't figure out how to use node.js code in vue.

Here's the vue file:

<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>
3

There are 3 best solutions below

0
Ali Nauman On BEST ANSWER

You need to update the DOM inside the Promise callback, although doing this via Vue may be preferable:

fetch("../src/markdown/About.md")
  .then((response) => response.text())
  .then((text) => {
    this.markdown = text;
    document.querySelector(".marked").innerHTML = marked.parse(this.markdown);
  });
0
abaumg On

With Vite, you can import assets as strings using the ?raw suffix and async/await:

const markdownFileContent = (await import(`path/to/markdown/file.md?raw`)).default;
const htmlString = marked.parse(markdownFileContent);
0
Kong On

This can be achieved using the ?raw suffix:

Importing Asset as String

Assets can be imported as strings using the ?raw suffix.

import markdownString from './shader.md?raw'

You will need to add the assets to your vite.config:

export default defineConfig({
   ...
   assetsInclude: ["**/*.md"],
}