@babel/plugin-proposal-bytes-modules
Transforms import ... with { type: "bytes" } declarations to platform-specific API to read the imported file as an immutable Uint8Array.
On platforms without support for immutable ArrayBuffers, Babel will return a Uint8Array backed by a mutable ArrayBuffer.
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 bytes from "./image.png" with { type: "bytes" };
will be transformed to
- Browsers
- Node.js (ESM)
- Node.js (CommonJS)
- Browsers and Node.js (ESM)
const bytes = await fetch(import.meta.resolve("./image.png"))
.then(r => r.bytes())
.then(_immutableUint8Array);
import { readFileSync as _readFileSync } from "fs";
const bytes = _immutableUint8Array(_readFileSync(new URL(import.meta.resolve("./image.png"))));
"use strict";
const bytes = _immutableUint8Array(require("fs").readFileSync(require.resolve("./image.png")));
const bytes = await (
typeof process === "object" && process.versions?.node
? import("fs").then(fs => fs.promises.readFile(new URL(import.meta.resolve("./image.png")))).then(_immutableUint8Array)
: fetch(import.meta.resolve("./image.png")).then(r => r.bytes()).then(_immutableUint8Array)
);
Namespace imports are also supported, and are compiled to an object with a single default property:
import * as ns from "./image.png" with { type: "bytes" };
Named imports are not valid for bytes modules, and will cause a compilation error.
Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-proposal-bytes-modules
yarn add --dev @babel/plugin-proposal-bytes-modules
pnpm add --save-dev @babel/plugin-proposal-bytes-modules
bun add --dev @babel/plugin-proposal-bytes-modules
Usage
With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-proposal-bytes-modules"]
}
Via CLI
babel --plugins=@babel/plugin-proposal-bytes-modules script.js
Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-bytes-modules"],
});