Unenv: Platform-Agnostic JavaScript Environment

1.10.0 · active · verified Sun Apr 19

Unenv is a framework-agnostic system designed to convert JavaScript code for platform-agnostic execution across various environments, including browsers, Web Workers, Node.js, and other JavaScript runtimes. The current stable version is `1.10.0`, though active development is focused on v2.0.0-rc, with frequent release candidates. Its key differentiators include providing comprehensive polyfills for Node.js built-in modules and common npm packages, and offering an auto-mocking proxy for APIs that are not natively supported or fully implemented in a target runtime. Unenv provides configurable presets for specific environments like Node, Nodeless, Deno, Cloudflare Workers, and Vercel Edge Functions, allowing seamless integration with popular bundlers such as Rollup, Webpack, Esbuild, and Rspack through alias, inject, and external configurations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure `unenv` using the `defineEnv` utility for a Cloudflare Workers environment. It shows how to enable Node.js compatibility, apply environment-specific presets, and inspect the generated aliases, injections, polyfills, and externalizations for use in bundlers. It also illustrates how `unenv` handles unimplemented Node.js APIs by providing a runtime error, preventing unexpected behavior.

import { defineEnv, nodeless, cloudflare } from 'unenv';
import fs from 'node:fs'; // Example of a Node.js built-in that will be shimmed

// Configure unenv for a Cloudflare Workers environment, enabling Node.js compatibility
// and auto-mocking for unimplemented APIs.
const { alias, inject, polyfill, external } = defineEnv({
  nodeCompat: true, // Enable shims for Node.js built-ins and globals
  npmShims: true,    // Enable shims for common npm packages
  presets: [
    nodeless,      // Base preset for non-Node.js environments
    cloudflare     // Cloudflare Workers specific compatibility
  ],
  overrides: {
    // Custom overrides if needed, e.g., to replace specific modules
    'node:fs': 'unenv/mock/proxy-cjs' // Ensure fs is fully mocked or aliased
  }
});

console.log('Generated Aliases:', alias);
console.log('Injected Globals:', inject);
console.log('Required Polyfills:', polyfill);
console.log('Externalized Modules:', external);

// This output can then be used in a bundler configuration (e.g., Vite, Webpack, Rollup)
// to apply the environment transformations.

// Example: How a bundler might use 'alias' output
// const viteConfig = {
//   resolve: {
//     alias: Object.entries(alias).map(([find, replacement]) => ({ find, replacement }))
//   }
// };
// console.log(viteConfig);

// Example: Demonstrate an unimplemented API call with a mock
try {
  fs.readFileSync('./test.txt', 'utf8');
} catch (e) {
  console.log(`
Attempted to use fs.readFileSync: ${e.message}`);
  console.log('This demonstrates how unenv mocks unimplemented APIs by throwing an error, indicating it is not available in the target runtime.');
}

view raw JSON →