Next.js+TypeScript跨项目引入外部源码及共享依赖的配置问题
解决Next.js+TypeScript跨项目组件共享的热重载与依赖共享问题
1. 简化TS配置(弃用Project References,直接识别源文件)
项目A的
tsconfig.json:- 在
include数组中加入B项目的路径,比如"../B/**/*",让TS直接识别B的组件源文件 - 确保
compilerOptions.jsx设置和B完全一致(比如都用Next.js默认的"preserve") - 不需要配置
references,因为直接本地引入源文件的场景下,references会强制TS寻找B的编译产物,反而破坏热重载和依赖共享逻辑
- 在
项目B的
tsconfig.json:- 对齐A的
compilerOptions.jsx设置,避免JSX编译规则冲突 - 开启
"skipLibCheck": true,跳过对外部依赖的类型检查,减少编译报错 - 修改
package.json,把react、react-dom、next设为peerDependencies,示例:
这样B独立开发时用"peerDependencies": { "react": "^18.x", "react-dom": "^18.x", "next": "^13.x || ^14.x" }, "devDependencies": { "react": "^18.x", "react-dom": "^18.x", "next": "^13.x" }devDependencies,被A引入时直接复用A的依赖
- 对齐A的
2. 配置Next.js确保转译与依赖共享
在项目A的next.config.js中,重点配置转译规则和webpack依赖解析:
const path = require('path'); /** @type {import('next').NextConfig} */ const nextConfig = { // 明确指定B的绝对路径,让Next.js转译B的TS/TSX代码 transpilePackages: [path.resolve(__dirname, '../B')], webpack: (config, { dev }) => { // 让webpack优先从A的node_modules找依赖,避免B无node_modules时的依赖缺失报错 config.resolve.modules.unshift(path.resolve(__dirname, 'node_modules')); // 强制react、react-dom等核心依赖使用A的版本,杜绝重复打包 config.resolve.alias = { ...config.resolve.alias, 'react': path.resolve(__dirname, 'node_modules/react'), 'react-dom': path.resolve(__dirname, 'node_modules/react-dom'), 'next': path.resolve(__dirname, 'node_modules/next'), }; // 开发模式下监听B的文件变化,触发热重载 if (dev) { config.watchOptions = { ...config.watchOptions, ignored: [ ...(config.watchOptions?.ignored || []), path.resolve(__dirname, '../B/node_modules') ], }; } return config; }, }; module.exports = nextConfig;
3. 修复react/jsx-dev-runtime找不到的问题
这个错误的核心是webpack编译B组件时,未从A的node_modules中找到对应模块,按以下步骤验证:
- 确认A的
node_modules中已安装react和react-dom(正常Next.js初始化项目默认包含) - 确保A的
next.config.js中已添加config.resolve.modules.unshift(...)配置,让webpack优先查找A的依赖 - 检查B的
tsconfig.json中jsx设置与A完全一致,避免JSX编译逻辑冲突
4. 验证效果
- 删除B的
node_modules和.next目录 - 启动A的开发服务器:
npm run dev - 修改B的
Editor.tsx组件,A的页面应自动热重载 - 执行
npm run build打包A,检查产物确认react等核心依赖仅打包一次
内容的提问来源于stack exchange,提问作者Andy Ray
相关产品推荐
相关产品推荐

