A polyfill for WHATWG URL and related APIs:
This package is a Node-API-based module that wraps the Ada native implementation of URL, so can be used in any JavaScript engine or runtime that supports Node-API.
To clarify, this project is not affiliated with WinterCG (i.e. is not an official work). It merely implements part of the WinterCG Common Minimum API proposal.
Install this npm package as follows:
npm install url-wintercg
Run this polyfill in your app's entrypoint file so that it fills in the APIs as early as possible in the app lifecycle.
import { polyfill } from "url-wintercg";
polyfill(globalThis);
// All implemented APIs will now be available in global scope
const url = new URL("https://example.com?foo=1&bar=2");
const params = new URLSearchParams(url.search);
console.log(params);
And for TypeScript typings, add the DOM
lib in tsconfig.json
:
{
"compilerOptions": {
"lib": ["DOM"],
// ...
}
}
Here, we import from the npm package each time we want to use an API, rather than polyfilling globally.
import { Event, EventTarget } from "url-wintercg";
const url = new URL("https://example.com?foo=1&bar=2");
const params = new URLSearchParams(url.search);
console.log(params);
Some limited TypeScript typings will be inferred from the library's JavaScript source code, but if you'd rather use the lib.dom.d.ts
typings built into TypeScript (which I would recommend), then:
-
Add the
DOM
lib intsconfig.json
:{ "compilerOptions": { "lib": ["DOM"], // ... } }
-
Do this little dance:
import { URL as URLImpl, URLSearchParams as URLSearchParamsImpl, } from "url-wintercg"; // Redeclare the implementation using the types from lib.dom.d.ts const URL = URLImpl as unknown as URL; const URLSearchParams = URLSearchParamsImpl as unknown as URLSearchParams; const url = new URL("https://example.com?foo=1&bar=2"); const params = new URLSearchParams(url.search); console.log(params);
This is my best-effort attempt to document usage with a bundler. These instructions are untested, so please open a PR if you find they need tweaking!
In all cases, you can set up TypeScript typings via adding the DOM
lib to your tsconfig.json
:
{
"compilerOptions": {
"lib": ["DOM"],
// ...
}
}
Below, I'll describe for each bundler how to integrate this package into your bundle.
This configuration ensures that all the implemented APIs are available from global scope:
const webpackConfig = {
plugins: [
new webpack.ProvidePlugin({
URL: ["url-wintercg", "URL"],
URLSearchParams: ["url-wintercg", "URLSearchParams"],
}),
],
};
Your JS engine/runtime must support:
- process.dlopen() (if using ESM)
- require() (if using CommonJS)
- Node-API