如何让基于Vite构建的React类库使用外部react-jsx-runtime?
如何让基于Vite构建的React类库使用外部react-jsx-runtime
要实现类库复用外部的react-jsx-runtime,避免重复打包,需要调整Vite配置和TS配置:
1. 更新Vite配置,把JSX运行时设为外部依赖
默认情况下,@vitejs/plugin-react会将react-jsx-runtime打包进类库产物里。你需要在rollupOptions的external数组中添加JSX运行时相关的包,同时在globals里对应声明全局变量,让类库从全局环境读取这些依赖:
// vite config export default defineConfig({ build: { lib: { entry: 'index.tsx', name: 'MyLib', fileName: 'index', }, rollupOptions: { // 添加JSX运行时到外部依赖列表 external: ['react', 'react-dom', 'react/jsx-runtime', 'react/jsx-dev-runtime'], output: { globals: { react: 'React', 'react-dom': 'ReactDOM', // 对应全局变量,和React的全局暴露一致 'react/jsx-runtime': 'ReactJSXRuntime', 'react/jsx-dev-runtime': 'ReactJSXDevRuntime' }, }, }, target: 'modules', }, plugins: [react(), dts({ outputDir: 'dist/types', include: ['./**/*.ts(x)?'], })], })
2. 确认TypeScript配置(如果用TS)
在tsconfig.json中确保JSX模式设置为react-jsx,这样TypeScript会生成引用外部JSX运行时的代码,而不是内嵌实现:
{ "compilerOptions": { // ...其他配置 "jsx": "react-jsx" } }
这样处理后,你的类库打包产物就不会包含react-jsx-runtime的代码,而是会从宿主环境的全局变量中获取,和react、react-dom一样作为外部依赖,彻底解决多个类库重复打包JSX运行时的问题。
内容的提问来源于stack exchange,提问作者Jannchie
相关产品推荐
相关产品推荐

