Next.js组件库打包报错:无法找到next/link模块
解决方案
一、解决next/link模块找不到问题
1. 统一TypeScript模块解析规则
在@flowershow/core的tsconfig.json和monorepo根目录的tsconfig.base.json中,同步配置模块解析规则,确保ES模块的后缀解析逻辑一致:
{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", "esModuleInterop": true, "skipLibCheck": true, "allowSyntheticDefaultImports": true } }
2. 调整Rollup配置自动补全后缀+标记外部依赖
使用Rollup插件自动给导入语句添加.js后缀,同时把Next.js、React相关包设为外部依赖(组件库无需打包这些核心依赖,由消费端提供):
// packages/core/rollup.config.js import resolve from '@rollup/plugin-node-resolve'; import sucrase from '@rollup/plugin-sucrase'; import addSuffix from 'rollup-plugin-add-suffix'; export default { input: 'src/index.ts', output: { dir: 'dist', format: 'esm', sourcemap: true }, plugins: [ resolve({ extensions: ['.ts', '.tsx', '.js', '.jsx'], preferBuiltins: false }), sucrase({ transforms: ['typescript', 'jsx'] }), addSuffix({ suffix: '.js' }) ], external: ['next/link', 'react', 'react-dom'] // 标记为外部依赖,避免打包进组件库 };
3. 配置package.json的ES模块入口与peer依赖
在@flowershow/core的package.json中声明模块类型、导出规则,并添加peer依赖确保消费端安装对应版本的Next.js:
{ "name": "@flowershow/core", "type": "module", "main": "./dist/index.js", "module": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { "import": "./dist/index.js" } }, "peerDependencies": { "next": "^13.x || ^14.x", "react": "^18.x", "react-dom": "^18.x" } }
二、解决Rollup导入语句在导出语句之后的问题
这个问题是Rollup默认的模块打包排序逻辑导致的,开启preserveModules选项保留原始模块结构即可:
// rollup.config.js - output部分 output: { dir: 'dist', format: 'esm', sourcemap: true, preserveModules: true, // 保留原始模块结构,避免导入导出顺序混乱 preserveModulesRoot: 'src' // 可选,指定模块根目录,让输出结构更清晰 }
三、Nx Monorepo适配配置
在@flowershow/core的project.json中,指定自定义Rollup配置文件,确保Nx使用正确的打包规则:
{ "targets": { "build": { "executor": "@nrwl/js:rollup", "options": { "rollupConfig": "packages/core/rollup.config.js", "outputPath": "dist/packages/core", "tsConfig": "packages/core/tsconfig.json" } } } }
同时在@flowershow/template的package.json中,使用Nx workspace依赖引用@flowershow/core:
{ "dependencies": { "@flowershow/core": "*" } }
内容的提问来源于stack exchange,提问作者olayway
相关产品推荐
相关产品推荐

