0

I'm using next.js with webpack 5 and all of a sudden my URL class import isn't working anymore.

Running npm run build gives the following error:

Attempted import error: 'URL' is not exported from 'url' (imported as 'URL').

The code in question is:

import { URL } from "url";
import { useEffect, useState } from "react";

const Error404 = () => {
  // Server side url class is undefined on client so choose based on which is available
  const Url = globalThis?.URL || URL;

  const defaultImageUrl = new Url(defaultImage, PUBLIC_URL).href;
...

I'm trying to use the WHATWG URL API because it's supposed to be a "Browser-compatible URL class"

This issue started in webpack 5 and was not present while using webpack 4. How do I fix my import such that webpack 5 doesn't give me the import error anymore?

Abir Taheer
  • 2,502
  • 3
  • 12
  • 34
  • Hi, how did you manage to fix this issue? I'm currently struggling with these 3 errors. Similar case scenario like yours, webpack 5. https://stackoverflow.com/questions/72651313/wrong-url-imports-for-sentry-library-in-a-react-rewired-app – Raül Jun 17 '22 at 08:23

1 Answers1

0

The URL constructor is accessible as a property on the global object, have you tried to use it without import?

Also, since your Error404 component is probably universal (should be available both server and client side), then you can't just use server-side modules, they might not compile for browser. Luckily, URL is not one of them, it can be used on both sides and even without import.

Danila
  • 15,606
  • 2
  • 35
  • 67