Search code examples
javascripttxtparceljs

How can I load a .txt file into JS with Parcel?


I'm trying to load an autogenerated (format is out of my control) data.txt file containing a number of 1 line quotes. I want to avoid preprocessing (ex making a script that turns the .txt file into a .json file) and import the txt file directly into my script code.

// @parcel/core: No transformers found for data.txt.
import data from "./data.txt"

const lines = data.split("\n")

for (const line of lines) {
    const spanElement = document.createElement("span")
    // ...set span element content and append to DIV
}

And yes, I've tried bundle inlining, but that's for bundles.

My main use case is to use this to make HTML elements to style like so:

<div class="quotes">
    <p>{a quote line}</p>
</div>

So I'm looking for how to import a txt file as a string into JS and turn it into DOM elements to add to my .quotes element. If there's a better way that I can load it in so I can avoid Client Side Rendering that would also be greately appreciated.


Solution

  • Use bundle-text:

    import data from "bundle-text:./data.txt" // works!
    
    const lines = data.split("\n")
    
    for (const line of lines) {
        const spanElement = document.createElement("span")
        // ...set span element content and append to DIV
    }