I am writing a (client-side) JavaScript library (a node/angular module). In this library, I make use of the URLSearchParams class.
const form = new URLSearch
If we want to support big range of nodejs
versions in our application , we could use some dirty code like this :
if(typeof URLSearchParams === 'undefined'){
URLSearchParams = require('url').URLSearchParams;
}
Note: It is not best practice to require
with a condition.
Update: Node v10 has built-in availability of URLSearchParams
on the global object so it can be used directly as anticipated in the question.
Older versions of Node:
One option is to set it as a global in the start-up script of the test runner:
import { URLSearchParams } from 'url';
global.URLSearchParams = URLSearchParams
With Jest, for example, you would use the setupTestFrameworkScriptFile to point to the above start-up script.
As a side note, if you wanted to achieve a similar outcome when creating a server-side Webpack bundle of universal code you can achieve this with the Webpack ProvidePlugin:
{
name: 'server',
target: 'node',
// ...
plugins: [
// ...
new webpack.ProvidePlugin({
URLSearchParams: ['url', 'URLSearchParams'],
fetch: 'node-fetch',
}),
],
}
You may use polifill @ungap/url-search-params https://www.npmjs.com/package/@ungap/url-search-params and for webpack may use @ungap/url-search-params/cjs
Old NodeJS 8 (which isused in AWS and GCloud) does not support URLSearchParams so this polifill helps.
In Node 10 when using TypeScript you may enable library dom which includes URLSearchParams implementation. Change tsconfig.json:
{
"compilerOptions": {
"lib": [
...
"dom"
...
]
}
}
In AWS Lambda which uses Node8.10, I had to do:
const {URLSearchParams} = require('url')
const sp = new URLSearchParams(request.querystring)
or
const url = require('url')
const sp = new url.URLSearchParams(request.querystring)