You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@ubilabs/google-maps-react-hooks时遇导入错误求助

解决@ubilabs/google-maps-react-hooks导入useState的模块错误

问题概述

使用@ubilabs/google-maps-react-hooks实现谷歌数据驱动样式时,遇到模块导入错误,提示无法从非ES模块导入命名导出useState。

错误信息

ERROR in ./node_modules/@ubilabs/google-maps-react-hooks/dist/index.modern.mjs 457:54-62
Can't import the named export 'useState' from non EcmaScript module (only default export is available)

相关代码

import React, { useState, useCallback, useRef, useEffect } from "react";
import {
  GoogleMapsProvider,
  GoogleMapsProviderProps,
  useAutocomplete,
  useGoogleMap,
} from "@ubilabs/google-maps-react-hooks";

解决方案

1. 配置Webpack处理ES模块

错误根源是Webpack未正确识别库中的ES模块代码,导致将React视为仅支持默认导出的CommonJS模块。在Webpack配置中添加规则,指定处理该库的.mjs文件:

module.exports = {
  module: {
    rules: [
      {
        test: /\.mjs$/,
        include: /node_modules\/@ubilabs\/google-maps-react-hooks/,
        type: 'javascript/auto'
      }
    ]
  }
};

如果使用Create React App,需借助react-app-rewired修改配置:

  • 安装依赖:npm install react-app-rewired --save-dev
  • 创建config-overrides.js文件并写入上述Webpack规则
  • 修改package.json中的启动脚本为react-app-rewired start/build/test

2. 升级库到最新版本

该问题可能是库的旧版本存在模块导出兼容问题,尝试升级到最新版:

npm update @ubilabs/google-maps-react-hooks

3. 临时应急方案(不推荐长期使用)

若上述方法无法快速生效,可临时修改库文件:

  1. 打开node_modules/@ubilabs/google-maps-react-hooks/dist/index.modern.mjs
  2. 将所有import { useState, ... } from 'react'替换为import React from 'react'
  3. 把代码中的useState改为React.useState,其他hooks同理

此方法需注意:每次重新安装依赖后需重复操作,仅作临时应急用。

内容的提问来源于stack exchange,提问作者Veera Silamban

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:05:11