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

Next.js中使用自定义.d.ts类型文件时出现模块找不到错误

问题描述

我用Next.js 15.2.4创建了React TypeScript项目,用到一个无官方类型定义的JS库,自己写了testfoo.d.ts类型文件。VS Code能正常识别类型,但构建时一直报错Module not found: Can't resolve 'testfoo'。

项目结构:

.next/
app/
node_modules/
public/
     assets/
            scripts/
                   testfoo.js
types/
     testfoo.d.ts
package.json
tsconfig.json

testfoo.d.ts内容:

// testfoo.d.ts
declare module "testfoo" {
  export interface ITest {
    disabled: boolean;
  }

  export class TestCl {
    constructor();
    go(): void;
  }
}

导入方式:

import { TestCl } from 'testfoo';

已尝试的操作:配置typeRoots、修改paths、导入testfoo.d、删除.next重新构建,均无效。

解决思路

问题核心:testfoo.js放在public目录下,该目录文件是静态资源(通过URL访问),Next.js的模块解析器不会将其当作可导入的模块处理。TypeScript能识别类型是因为.d.ts的声明,但打包工具webpack找不到实际JS文件,才会报错。

方案一:迁移JS文件到源码目录

  • 在项目根目录新建lib或utils目录,将testfoo.js移入,比如lib/testfoo.js
  • 保留types/testfoo.d.ts内容不变
  • 导入时使用路径别名:import { TestCl } from '@/lib/testfoo'(你的tsconfig.json已配置@/*指向./,可直接生效)

方案二:配置webpack别名指向public中的JS文件

  • 项目根目录创建/修改next.config.js,添加webpack别名配置:
/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.resolve.alias['testfoo'] = './public/assets/scripts/testfoo.js';
    return config;
  },
};

module.exports = nextConfig;
  • 重启Next.js开发服务后重新构建

方案三:修改类型声明的路径映射

  • 修改testfoo.d.ts的模块声明为实际路径:
declare module '@/public/assets/scripts/testfoo' {
  export interface ITest {
    disabled: boolean;
  }

  export class TestCl {
    constructor();
    go(): void;
  }
}
  • 导入时使用对应路径:
import { TestCl } from '@/public/assets/scripts/testfoo';
  • 注:若webpack无法解析该路径,需配合next.config.js添加相同路径的别名配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:20:57