node.jsnativescriptpolyfillswebpack-5

Is it possible to use node url in NativeScript app?


Is there a way to use URL in a NS 8 + webpack 5 app?

If I do this

import { URL } from 'url';

const url = new URL("https://stackoverflow.com");

I get warning export 'URL' (imported as 'URL') was not found in 'url' (possible exports: Url, format, parse, resolve, resolveObject) when compiling and runtime error url__WEBPACK_IMPORTED_MODULE_1__.URL is not a constructor

I tried add below in webpack.config.js but doesn't help

  nsWebpack.chainWebpack(config => {
    config.resolve.set('fallback', { url: require.resolve('url/') });
  });

Thanks!


Solution

  • I had the same problem. It might need some additional Webpack and/or TS config but could not figure out what exactly. In the end, I used an npm package to parse the URLs since I did not want to write a custom parser myself.

    The best option is to use - https://www.npmjs.com/package/whatwg-url - however, that also did not build correctly at the time of using it (NS 8.5.1, node v16.20) outputting errors in NativeScript.

    Another solution is https://www.npmjs.com/package/parse-url - but that uses the URL, so it had the same problem after all.

    So, I finally used successfully the https://www.npmjs.com/package/url-parse