Vite打包React组件库遇Framer Motion TypeScript类型错误求助
解决Vite打包React组件库时framer-motion的TypeScript类型错误
问题分析
你遇到的错误本质是TypeScript在推断styled(motion.div)的类型时,意外引用了关联工作区theme中的framer-motion包,而非组件库自身依赖的版本。这是因为monorepo的模块解析机制会自动向上查找node_modules,再加上你将framer-motion设为peerDependencies(本地不会自动安装),导致TS类型解析路径混乱。
解决方案
1. 给组件添加显式类型注解
错误提示明确要求添加类型注解,直接显式定义组件的props类型,避免TS自动推断时跨工作区查找类型:
import styled from 'styled-components' import { motion } from 'framer-motion' import type { MotionDivProps } from 'framer-motion/dom' // 合并自定义StyledProps与motion.div的原生props类型 type WrapperProps = MotionDivProps & StyledProps export const Wrapper = styled(motion.div)<WrapperProps>` ... Styling Here `
2. 配置TypeScript强制指定framer-motion的解析路径
在组件库的tsconfig.json中添加paths配置,让TS优先使用当前包node_modules中的framer-motion类型:
{ "compilerOptions": { // 其他配置... "paths": { "framer-motion": ["./node_modules/framer-motion"] } } }
3. 给组件库添加devDependencies版本的framer-motion
由于peerDependencies不会自动安装,本地开发时TS无法找到类型文件,因此需要在devDependencies中安装同版本的framer-motion,保证本地类型检查正常:
{ "peerDependencies": { "framer-motion": "10.12.4" }, "devDependencies": { "framer-motion": "10.12.4" } }
4. 优化Vite打包配置,明确external依赖
在vite.config.ts中把framer-motion设为external,避免打包时将其纳入产物,同时让类型解析逻辑更清晰:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], build: { lib: { entry: 'src/index.ts', name: 'YourComponentLibrary', formats: ['es', 'umd'] }, rollupOptions: { // 标记peer依赖为外部依赖 external: ['framer-motion', 'styled-components'], output: { // 全局变量映射,用于UMD格式 globals: { 'framer-motion': 'framerMotion', 'styled-components': 'styled' } } } } })
内容的提问来源于stack exchange,提问作者Jason McFarlane
相关产品推荐
相关产品推荐

