Unenv is a framework agnostic system that allows converting JavaScript code to be platform agnostic and working in any environment including Browsers, Workers, Node.js or pure JavaScript runtime.
# Using npm
npm i -D unenv
# Using yarn
yarn add --dev unenv
Using env utility and builtin presets ( and nodeless), unenv will provide an abstract config that can be used in building pipelines (rollup.js, webpack, etc)
import { env, node, nodeless } from 'unenv'
const { alias, inject, polyfill, external } = env(...presets)
nodeSuitable to convert universal libraries working in Node.js. (preset)
fetch APInodelessUsing this preset, we can convert a code that is depending on Node.js to work anywhere else.
Unenv provides a replacement for all Node.js built-ins for cross-platform compatiblity.
Unenv provides a replacement for common npm packages for cross platform compatibility.
| Package | Status | Source |
|---|---|---|
| npm/consola | Use native console |
unenv/runtime/npm/consola |
| npm/cross-fetch | Use native fetch |
unenv/runtime/npm/cross-fetch |
| npm/debug | Mocked with console.debug |
unenv/runtime/npm/debug |
| npm/fsevents | Mocked | unenv/runtime/npm/fsevents |
| npm/inherits | Inlined | unenv/runtime/npm/inherits |
| npm/mime-db | Minimized | unenv/runtime/npm/mime-db |
| npm/mime | Minimized | unenv/runtime/npm/mime |
| npm/node-fetch | Use native fetch |
unenv/runtime/npm/node-fetch |
| npm/whatwg-url | Use native URL |
unenv/runtime/npm/whatwg-url |
import MockProxy from 'unenv/runtime/mock/proxy'
console.log(MockProxy().foo.bar()[0])
Above package doesn’t works outside of Node.js and neither we need any platform specific logic! When aliasing os to mock/proxy-cjs, it will be auto mocked using a Proxy Object which can be recursively traversed like an Object, called like a Function, Iterated like an Array, or instantiated like a Class.
We use this proxy for auto mocking unimplemented internals. Imagine a packages does this:
const os = require('os')
if (os.platform() === 'windows') { /* do some fix */ }
module.exports = () => 'Hello world'
By aliasing os to unenv/runtime/mock/proxy-cjs, code will be compatible in other platforms.
Please check ./src/runtime to discover other polyfills.
MIT