Rollup打包报错:无法解析.js/.jsx文件引用的解决方案求助
解决Rollup混合打包.js/.jsx/.ts文件的"Could not resolve"错误
问题根源
你遇到的错误本质是Rollup无法正确解析非TypeScript文件的路径,同时类型定义文件(.d.ts)的生成路径或引用逻辑出现混乱,导致打包时无法匹配到对应的源文件。
解决方案步骤
1. 安装必要的依赖插件
确保你安装了以下核心插件,覆盖路径解析、TypeScript处理和JSX编译需求:
npm install --save-dev @rollup/plugin-typescript @rollup/plugin-node-resolve @rollup/plugin-commonjs typescript @babel/preset-react
2. 调整Rollup配置文件(rollup.config.js)
修改配置,添加路径解析规则、TypeScript类型生成逻辑,并确保Babel覆盖所有需要编译的文件类型:
import babel from '@rollup/plugin-babel'; import resolve from '@rollup/plugin-node-resolve'; import typescript from '@rollup/plugin-typescript'; import commonjs from '@rollup/plugin-commonjs'; export default { input: 'src/index.ts', output: [ { dir: 'dist/esm', format: 'esm', sourcemap: true, }, { dir: 'dist/cjs', format: 'cjs', sourcemap: true, }, ], plugins: [ // 配置路径解析,支持多种文件扩展名 resolve({ extensions: ['.js', '.jsx', '.ts', '.tsx'], browser: true, // 前端库需开启此选项 }), // 转换CommonJS模块为ES模块 commonjs(), // 处理TypeScript并生成类型定义,单独指定类型输出目录 typescript({ tsconfig: './tsconfig.json', declaration: true, declarationDir: 'dist/types', }), // 编译JSX与ES语法,覆盖所有目标文件类型 babel({ babelHelpers: 'bundled', extensions: ['.js', '.jsx', '.ts'], presets: [ '@babel/preset-react', // 注意版本与你的旧版React兼容 // 若需转译ES6+语法,添加@babel/preset-env并配置targets ], }), ], external: ['react', 'react-dom'], // 排除外部依赖,不打包进库文件 };
3. 配置tsconfig.json
调整TypeScript配置,允许处理JS/JSX文件,并正确生成类型定义:
{ "compilerOptions": { "target": "ES2018", "module": "ESNext", "moduleResolution": "Node", "jsx": "react", // 适配旧版React的JSX转换规则 "declaration": true, "declarationDir": "./dist/types", "outDir": "./dist", "allowJs": true, // 允许TypeScript解析JS/JSX文件 "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }
4. 修正index.ts中的导出路径
确保导出语句的路径正确,建议显式添加扩展名(若moduleResolution未设为NodeNext):
// 错误示例(易导致解析失败) // export { default as ComponentA } from './components/ComponentA'; // 正确示例 export { default as ComponentA } from './components/ComponentA.jsx'; export { utilFunc } from './utils/helper.js'; export { default as TypeComponent } from './components/TypeComponent.ts';
若不想添加扩展名,需确保tsconfig的moduleResolution设为Node或NodeNext,同时Rollup的resolve插件已配置对应扩展名。
5. 重新执行打包
清理旧打包产物后重新执行命令:
rm -rf dist && rollup -c
关键注意事项
- 确保
@babel/preset-react版本与你的旧版React兼容,比如React 16对应@babel/preset-react@^7.18.6 - 若JS文件使用ES6+语法,需添加
@babel/preset-env到Babel预设,并配置targets适配目标环境 - 在package.json中配置类型与入口字段,方便用户引入:
{ "types": "dist/types/index.d.ts", "module": "dist/esm/index.js", "main": "dist/cjs/index.js" }
内容的提问来源于stack exchange,提问作者afriedman111
相关产品推荐
相关产品推荐

