【问题标题】:How can I load a .txt file into JS with Parcel?如何使用 Parcel 将 .txt 文件加载到 JS 中?
【发布时间】:2022-11-14 04:38:12
【问题描述】:

我正在尝试加载包含许多 1 行引号的自动生成(格式不受我控制)data.txt 文件。我想避免预处理(例如制作一个将 .txt 文件转换为 .json 文件的脚本)并将 txt 文件直接导入我的脚本代码中。

// @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
}

是的,我试过bundle inlining,但那是捆绑的。

我的主要用例是使用它来使 HTML 元素具有如下样式:

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

所以我正在寻找如何将txt 文件作为字符串导入JS 并将其转换为DOM 元素以添加到我的.quotes 元素中。如果有更好的方法可以加载它,那么我可以避免Client Side Rendering,这也将不胜感激。

【问题讨论】:

    标签: javascript txt parcel


    【解决方案1】:

    使用bundle-text:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多