{"id":12278,"library":"unenv","title":"Unenv: Platform-Agnostic JavaScript Environment","description":"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.","status":"active","version":"1.10.0","language":"javascript","source_language":"en","source_url":"https://github.com/unjs/unenv","tags":["javascript","typescript"],"install":[{"cmd":"npm install unenv","lang":"bash","label":"npm"},{"cmd":"yarn add unenv","lang":"bash","label":"yarn"},{"cmd":"pnpm add unenv","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This is the primary entry point for configuring environments in `unenv` v2.x. `unenv` is ESM-first, and CommonJS `require` is generally not supported for v2 API.","wrong":"const { defineEnv } = require('unenv')","symbol":"defineEnv","correct":"import { defineEnv } from 'unenv'"},{"note":"This was the primary entry point for `unenv` v1.x. For new projects or migrating to v2, `defineEnv` is recommended.","symbol":"env","correct":"import { env } from 'unenv'"},{"note":"Environment presets (e.g., `nodeless`, `cloudflare`, `deno`, `node`) are directly named exports from the `unenv` package. For specific Cloudflare Workers presets, `@cloudflare/unenv-preset` may be used.","wrong":"import { presets } from 'unenv' // Presets are named exports","symbol":"nodeless, cloudflare","correct":"import { nodeless, cloudflare } from 'unenv'"},{"note":"For Node.js built-ins, `unenv` provides shims via subpath exports under `unenv/node/`. Direct imports like `import { Buffer } from 'buffer'` might resolve to Node.js native modules and break in non-Node environments without `unenv`'s intervention.","wrong":"import { Buffer } from 'buffer'","symbol":"Buffer","correct":"import { Buffer } from 'unenv/node/buffer'"}],"quickstart":{"code":"import { defineEnv, nodeless, cloudflare } from 'unenv';\nimport fs from 'node:fs'; // Example of a Node.js built-in that will be shimmed\n\n// Configure unenv for a Cloudflare Workers environment, enabling Node.js compatibility\n// and auto-mocking for unimplemented APIs.\nconst { alias, inject, polyfill, external } = defineEnv({\n  nodeCompat: true, // Enable shims for Node.js built-ins and globals\n  npmShims: true,    // Enable shims for common npm packages\n  presets: [\n    nodeless,      // Base preset for non-Node.js environments\n    cloudflare     // Cloudflare Workers specific compatibility\n  ],\n  overrides: {\n    // Custom overrides if needed, e.g., to replace specific modules\n    'node:fs': 'unenv/mock/proxy-cjs' // Ensure fs is fully mocked or aliased\n  }\n});\n\nconsole.log('Generated Aliases:', alias);\nconsole.log('Injected Globals:', inject);\nconsole.log('Required Polyfills:', polyfill);\nconsole.log('Externalized Modules:', external);\n\n// This output can then be used in a bundler configuration (e.g., Vite, Webpack, Rollup)\n// to apply the environment transformations.\n\n// Example: How a bundler might use 'alias' output\n// const viteConfig = {\n//   resolve: {\n//     alias: Object.entries(alias).map(([find, replacement]) => ({ find, replacement }))\n//   }\n// };\n// console.log(viteConfig);\n\n// Example: Demonstrate an unimplemented API call with a mock\ntry {\n  fs.readFileSync('./test.txt', 'utf8');\n} catch (e) {\n  console.log(`\nAttempted to use fs.readFileSync: ${e.message}`);\n  console.log('This demonstrates how unenv mocks unimplemented APIs by throwing an error, indicating it is not available in the target runtime.');\n}\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Migrate `import { env } from 'unenv'` to `import { defineEnv } from 'unenv'` and adjust configuration object structure accordingly. Refer to the `unenv` v2 documentation.","message":"The `env` utility from v1.x has been replaced by `defineEnv` in `unenv` v2.x. While v1.x is stable, new projects or migrations should use `defineEnv` for enhanced configuration options and future compatibility.","severity":"breaking","affected_versions":">=2.0.0-rc"},{"message":"Some Node.js APIs are not fully implemented by `unenv` for all target runtimes. Instead, `unenv` might provide 'mock' implementations that throw errors or do nothing when called. This prevents silent failures but requires developers to be aware of unsupported APIs.","severity":"gotcha"},{"message":"When targeting Cloudflare Workers, ensure that the `nodejs_compat` or `nodejs_compat_v2` compatibility flag is enabled in your `wrangler.toml` configuration. Without this, Node.js API polyfills might not function correctly or be included.","severity":"gotcha"},{"message":"Presets like `deno` and `cloudflare` in `unenv` v2.x are explicitly marked as 'experimental' and their behavior or API might change in future release candidates or stable versions. Use with caution in production environments.","severity":"deprecated"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `unenv` is correctly configured in your build pipeline to provide shims and aliases for Node.js built-ins. For `defineEnv`, set `nodeCompat: true`. If using a specific preset like `nodeless` or `cloudflare`, ensure it's applied.","cause":"An npm package attempting to import a Node.js built-in module (like `events`, `path`, `fs`) in a non-Node.js environment (e.g., browser, worker) without `unenv` properly shimming or aliasing it.","error":"Could not resolve \"events\""},{"fix":"Identify the unsupported Node.js API. If the functionality is critical, you may need to implement a custom shim using `unenv`'s `overrides` option or find an alternative, platform-agnostic library. Review `unenv`'s documentation for supported API coverage per runtime.","cause":"Calling a method of a Node.js API (e.g., `fs.readFileSync`) that `unenv` has provided a mock implementation for, but the actual functionality is not available or polyfilled in the target runtime.","error":"[unenv] <method name> is not implemented yet!"}],"ecosystem":"npm"}