React+TypeScript跨端组件库构建报错:Expected 'from' got 'typeof'
问题分析与解决方案
问题原因
报错核心是Rollup尝试编译react-native的源码文件,但其中的import typeof是TypeScript专属语法,当前配置下的rollup-plugin-typescript2未正确处理node_modules中的这类语法。更关键的是,react-native作为类库的peer依赖,本就不该被打包进你的产物,应由使用该类库的宿主项目提供。
解决步骤
1. 确保react-native在peerDependencies中
打开package.json,确认react-native被添加到peerDependencies(没有的话直接补充),让rollup-plugin-peer-deps-external自动将其排除在打包范围外:
{ "peerDependencies": { "react": "^18.0.0", "react-native": "^0.70.0" } }
2. 手动配置Rollup的external选项
在rollup.config.js中添加external配置,明确排除react-native及其相关依赖,避免Rollup去编译它的源码:
export default { input: 'src/index.ts', // 新增external配置 external: ['react', 'react-native', 'react-native/*'], output: [ { file: pkg.main, format: 'cjs', sourcemap: true, }, { file: pkg.module, format: 'esm', sourcemap: true, }, ], plugins: [ del({ targets: 'dist/*' }), peerDepsExternal(), resolve(), commonjs(), typescript({ tsconfig: 'tsconfig.build.json', useTsconfigDeclarationDir: true, }), postcss(), ], };
3. 调整TypeScript配置
修改tsconfig.build.json,添加skipLibCheck: true跳过第三方库的类型检查,避免react-native的类型定义引发冲突:
{ "compilerOptions": { // 保留原有配置... "skipLibCheck": true, "moduleResolution": "node" }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }
4. 规范组件导入逻辑
确保Native组件只导入需要的特定API,避免意外引入整个react-native源码:
// 正确写法 import { View, Text } from 'react-native';
原理说明
通过将react-native标记为外部依赖,Rollup会跳过对其源码的编译,保留导入语句交由宿主项目处理。skipLibCheck则避免了TypeScript检查第三方库类型时的报错,确保编译流程顺畅。
内容的提问来源于stack exchange,提问作者fordat
相关产品推荐
相关产品推荐

