0

Is there any way to get Deno to import a text file (using import syntax)?

e.g.:

import { body } from "./somefile.txt"

// error: Expected a JavaScript or TypeScript module, 
//   but identified a Unknown module. Importing these
//   types of modules is currently not supported.
//  Specifier: file:///foo/somefile.txt

Using tsc this would be configurable but I suspect it might just be impossible in Deno?

1

1 Answer 1

3

Deno does not currently support loading plaintext resources using import (static or dynamic).

There is the import attributes proposal which allows for importing of different types of module resources by using the with keyword, but plaintext content is not currently supported.


Using tsc this would be configurable

The TypeScript compiler currently supports resolving JSON resources using import syntax via the compiler option resolveJsonModule, but it does not support plaintext content.

Some bundlers (e.g. esbuild, rollup, webpack) support the concept of loaders/plugins, which can override the behavior of import statements in source code. Node.js offers a similar feature: module customization hooks.

On this topic: there is a GitHub issue in the Deno repository: denoland/deno#8327 — Proposal: Module Loader API.


The standard method of loading text content in a JavaScript module is to use the text() method on a response returned by the global fetch() method:

const text = await (await fetch("./somefile.txt")).text();

Some JS runtimes offer specialized APIs in addition to the above — for example, Deno offers Deno.readTextFile and Deno.readTextFileSync:

const text = await Deno.readTextFile("./somefile.txt");
1
  • Note: there’s a new PR related to this: denoland/deno_core#402 — I’ll try to keep track of whether it’s merged into Deno and released, and then update this answer.
    – jsejcksn
    Commented Jan 6, 2024 at 21:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.