【问题标题】:Unable to import URL class from node 'url' module in Next.JS无法从 Next.JS 中的节点“url”模块导入 URL 类
【发布时间】:2021-07-21 12:49:24
【问题描述】:

我正在使用带有 webpack 5 的 next.js,突然间我的 URL 类导入不再工作了。

运行npm run build 会出现以下错误:

尝试导入错误:“URL”未从“url”导出(导入为“URL”)。

有问题的代码是:

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;
...

我正在尝试使用WHATWG URL API,因为它应该是"Browser-compatible URL class"

这个问题从 webpack 5 开始,在使用 webpack 4 时不存在。 如何修复我的导入,以便 webpack 5 不再给我导入错误?

【问题讨论】:

    标签: javascript node.js webpack next.js webpack-5


    【解决方案1】:

    URL 构造函数可作为全局对象上的属性访问,您是否尝试过在不导入的情况下使用它?

    另外,由于您的Error404 组件可能是通用的(应该​​在服务器端和客户端都可用),那么您不能只使用服务器端模块,它们可能无法为浏览器编译。幸运的是,URL 不是其中之一,它可以在两边使用,甚至可以不导入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2020-10-31
      • 2023-03-09
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多