Next.js 14导入自定义npm库函数时出现模块找不到错误求助
问题排查与解决方案
核心问题分析
你的tsup配置给所有JS输出文件加了全局"use client" banner,导致Next.js将整个npm包标记为客户端专属代码,但Server Action运行在服务器端环境,Next.js在服务器端构建时无法解析客户端代码,因此触发"Module not found"错误。
额外原因:仅导入类型时,TypeScript编译阶段会移除类型代码;导入函数但不调用时,Tree Shaking会剔除未使用的代码,这两种情况都不会触发实际模块加载,因此不会报错。
解决方案步骤
1. 移除tsup全局"use client" banner
全局强制标记客户端代码会导致包无法在服务器端使用,仅对客户端专属函数单独添加'use client'注释即可。修改后的tsup配置:
import { defineConfig } from "tsup" export default defineConfig({ entry: ['src/index.ts'], outDir: 'dist', format: ['esm', 'cjs'], dts: true, sourcemap: true, clean: true, target: 'esnext', external: ['react', 'next'], // 移除全局banner配置 });
如果包中有客户端专属逻辑,在对应文件顶部单独标记:
// src/client-functions.ts 'use client'; export function clientOnlyLogic() { // 仅客户端运行的代码 }
2. 完善npm包的package.json配置
确保Next.js能正确识别模块入口,添加/修正以下字段:
{ "name": "@bpmromandie/kyc_common_types", "version": "x.x.x", "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { "import": "./dist/index.js", "require": "./dist/index.cjs", "types": "./dist/index.d.ts" } }, "files": ["dist"] }
exports字段是关键,Next.js模块解析会优先读取该字段,确保ESM/CJS入口正确对应dist目录的输出文件。
3. 重新构建并更新包
执行构建后,重新发布到npm或本地link:
npm run build # 本地测试:重新执行npm link(包目录)和npm link @bpmromandie/kyc_common_types(Next.js项目) # 线上使用:重新发布后在Next.js项目执行 npm install @bpmromandie/kyc_common_types@latest
4. 正常在Server Action中使用
确保Server Action标记为'use server',直接导入函数即可:
// app/actions.ts 'use server'; import { simpleSum } from '@bpmromandie/kyc_common_types'; export async function myServerAction() { const sumResult = simpleSum(1, 2); // 服务器端逻辑... }
内容的提问来源于stack exchange,提问作者Maurizio Manca
相关产品推荐
相关产品推荐

