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

使用detectincognitojs遇TS2306错误:声明文件非模块

问题原因

这个报错的核心是detectincognitojs的TypeScript声明文件写法不符合ES模块规范——它把detectIncognito声明成了全局变量,而非模块导出成员,所以你用import { detectIncognito }这种解构导入的方式时,TypeScript会判定该文件不是合法模块,抛出2306错误。

解决方案

你有两种可行的修复方式:

方式1:自定义类型声明文件(推荐)

在项目的src目录下创建types/detectincognitojs.d.ts文件,内容如下:

declare module "detectincognitojs" {
  export function detectIncognito(): Promise<{
    isPrivate: boolean;
    browserName: string;
  }>;
}

保存后,就能正常使用官方文档里的导入语句:

import { detectIncognito } from "detectincognitojs";

// 调用示例
detectIncognito().then(result => {
  console.log(result.isPrivate, result.browserName);
});

如果习惯用默认导入,可将自定义声明改成:

declare module "detectincognitojs" {
  export default function detectIncognito(): Promise<{
    isPrivate: boolean;
    browserName: string;
  }>;
}

对应的导入语句调整为:

import detectIncognito from "detectincognitojs";

方式2:直接使用全局变量

先通过导入语句加载包:

import "detectincognitojs";

然后直接调用全局的detectIncognito()函数。如果TypeScript提示找不到该全局变量,可在自定义声明文件里补充全局声明:

declare global {
  function detectIncognito(): Promise<{
    isPrivate: boolean;
    browserName: string;
  }>;
}

export {};
补充说明

这个问题属于包本身的TypeScript声明文件缺陷,和你的create-react-app TS模板无关——哪怕是最小复现项目也会触发,因为包的.d.ts文件没有按照ES模块规范导出成员。自定义声明文件是最稳妥的解决方式,无需修改node_modules内的内容,避免后续依赖更新覆盖修改。

内容的提问来源于stack exchange,提问作者Michael K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:10:26