[英]Unable to import URL class from node 'url' module in Next.JS
I'm using next.js with webpack 5 and all of a sudden my URL class import isn't working anymore.我将 next.js 与 webpack 5 一起使用,突然间我的 URL ZA2F2ED4FDC40 不再工作了。
Running npm run build
gives the following error:运行npm run build
会出现以下错误:
Attempted import error: 'URL' is not exported from 'url' (imported as 'URL').尝试导入错误:“URL”未从“url”导出(导入为“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"
我正在尝试使用WHATWG URL API因为它应该是"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?此问题始于 webpack 5 并且在使用 webpack 4 时不存在。如何修复我的导入,以便 webpack 5 不再给我导入错误?
The URL
constructor is accessible as a property on the global object, have you tried to use it without import? URL
构造函数可作为全局 object 上的属性访问,您是否尝试在不导入的情况下使用它?
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.此外,由于您的Error404
组件可能是通用的(应该在服务器端和客户端都可用),那么您不能只使用服务器端模块,它们可能无法为浏览器编译。 Luckily, URL
is not one of them, it can be used on both sides and even without import.幸运的是, URL
不是其中之一,它可以双面使用,甚至无需导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.