发布SolidJS TypeScript组件至npm后引入报错:React未定义
问题解决方法
1. 修正package.json配置
- 确保
peerDependencies仅声明SolidJS依赖,移除任何React相关依赖:"peerDependencies": { "solid-js": "^1.7.0" }, "dependencies": { // 不要包含react、react-dom,除非组件确实依赖 } - 补充SolidJS专属字段并修正入口路径,让构建工具识别这是Solid组件包:
"main": "./dist/index.cjs", "module": "./dist/index.js", "types": "./dist/index.d.ts", "type": "module", "solid": "./dist/index.js"
2. 调整tsconfig.json配置
- 确保JSX相关配置指向SolidJS,而非React:
"compilerOptions": { "jsx": "solid", "jsxImportSource": "solid-js", "target": "ESNext", "module": "ESNext", "moduleResolution": "bundler", "declaration": true, "outDir": "./dist" } - 精准控制源码范围,排除app目录避免编译混淆:
"include": ["src/**/*"], "exclude": ["node_modules", "../app"]
3. 优化打包工具配置(以Vite为例)
如果使用Vite打包组件,需配置为库模式并明确排除SolidJS依赖:
import { defineConfig } from 'vite'; import solidPlugin from 'vite-plugin-solid'; export default defineConfig({ plugins: [solidPlugin()], build: { lib: { entry: './src/index.ts', formats: ['es', 'cjs'], fileName: (format) => `index.${format}.js` }, rollupOptions: { external: ['solid-js'], output: { globals: { 'solid-js': 'SolidJS' } } } } });
4. 清理缓存重新安装
- 卸载现有包:
npm uninstall your-solid-component-package - 清理npm缓存:
npm cache clean --force - 重新安装包:
npm install your-solid-component-package - 重启开发服务器,确保旧编译产物被清除
SolidJS TypeScript包发布指导
1. 项目结构规范
- 保持
app(示例应用)与package(组件源码)完全分离,package目录作为独立npm包根目录 - package目录下用
src存放组件源码,dist存放编译后的产物
2. 编译与打包
- 使用Vite或Rollup配合
solid-plugin打包,同时输出ES模块和CommonJS两种格式,适配不同项目导入需求 - 开启TypeScript的
declaration: true配置,自动生成类型声明文件,方便TS项目使用
3. package.json核心字段配置
name:确保包名在npm registry中唯一version:遵循语义化版本规范(如1.0.0、1.0.1)files:指定发布到npm的文件列表,避免冗余文件:"files": ["dist", "README.md"]- 必须包含
main、module、types、solid字段,明确不同场景下的入口路径
4. 发布流程
- 登录npm账号:
npm login(确认使用官方registry) - 在package目录下执行编译命令:
npm run build - 发布包:
npm publish(首次发布需验证包名,后续发布前需更新版本号)
内容的提问来源于stack exchange,提问作者Felipe Chernicharo
相关产品推荐
相关产品推荐

