@babel/plugin-proposal-text-modules
Transforms import ... with { type: "text" } declarations to platform-specific API to read the imported file and decode it as UTF-8 text.
The transformation applied by this plugin depends on your top-level targets to detect whether the generated code should be compatible with Node.js, browsers, or both. When targeting Node.js, the generated code will also change depending on whether you are compiling modules to CommonJS or not.
This plugin cannot be used when compiling modules to AMD, SystemJS, or UMD.
This plugin only transforms import declarations and not dynamic import() calls.
Example
import banner from "./banner.txt" with { type: "text" };
will be transformed to
- Browsers
- Node.js (ESM)
- Node.js (CommonJS)
- Browsers and Node.js (ESM)
const banner = await fetch(import.meta.resolve("./banner.txt")).then(r => r.text());
import { readFileSync as _readFileSync } from "fs";
const banner = String(_readFileSync(new URL(import.meta.resolve("./banner.txt"))));
"use strict";
const banner = String(require("fs").readFileSync(require.resolve("./banner.txt")));
const banner = await (
typeof process === "object" && process.versions?.node
? import("fs").then(fs => fs.promises.readFile(new URL(import.meta.resolve("./banner.txt")))).then(String)
: fetch(import.meta.resolve("./banner.txt")).then(r => r.text())
);
Namespace imports are also supported, and are compiled to an object with a single default property:
import * as ns from "./banner.txt" with { type: "text" };
Named imports are not valid for text modules, and will cause a compilation error.
Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-proposal-text-modules
yarn add --dev @babel/plugin-proposal-text-modules
pnpm add --save-dev @babel/plugin-proposal-text-modules
bun add --dev @babel/plugin-proposal-text-modules
Usage
With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-proposal-text-modules"]
}
Via CLI
babel --plugins=@babel/plugin-proposal-text-modules script.js
Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-text-modules"],
});