Text imports
You can now import a file as a JavaScript string using the new text import attribute.
import text from "/file.txt" with { type: "text" };
As with other import types like JSON and CSS, text modules can be dynamic:
const button = document.querySelector('button');
const div = document.querySelector('div');
button.addEventListener('click', async function() {
const text = await import('/file.txt', { with: { type: 'text' } });
div.textContent = text.default;
});
The imported file could be pretty much anything — it need not be a .txt file. You could import a CSV file or a YAML file, for example.
Here’s an example that imports a HTML file and inserts it into the page:
import partial from '/partial.html' with {type: "text"};
const div = document.querySelector('div');
div.setHTML(partial, {sanitizer: {}});
For a documentation website you could import a CSS, JavaScript or SVG file and display it as plain text:
import text from "/plus-icon.svg" with { type: "text" };
const div = document.getElementById('target');
div.textContent = text;
Fetch comparison
fetch() can be used for the same purpose, but is always async.
let response = await fetch("file.txt");
let text = await response.text();
Browser support
This feature is currently supported in Bun, Deno and Firefox Nightly.