You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue组件库作为NPM包使用时出现React is not defined错误

解决Vue组件库TSX自定义指令引入后"React is not defined"错误

以下是几个关键的配置缺失点及修复方案:

  • 库的package.json未声明JSX依赖源
    消费项目无法自动识别你的库使用Vue JSX,会默认按React JSX处理。在库的package.json中添加字段:

    "jsxImportSource": "vue"
    
  • 库的Vite打包配置未明确JSX导入源
    确保库的vite.config.ts中,vue-jsx插件明确指定jsxImportSource,避免打包时遗漏Vue JSX运行时关联:

    import { defineConfig } from 'vite'
    import vueJsx from '@vitejs/plugin-vue-jsx'
    
    export default defineConfig({
      plugins: [
        vueJsx({
          jsxImportSource: 'vue'
        })
      ],
      build: {
        lib: {
          entry: 'src/index.ts',
          name: 'YourComponentLib',
          fileName: (format) => `your-lib.${format}.js`
        },
        rollupOptions: {
          external: ['vue'],
          output: {
            globals: {
              vue: 'Vue'
            }
          }
        }
      }
    })
    
  • 排查库中TSX文件的隐性React依赖
    检查你的.tsx文件中是否存在无意引入React的代码(比如import React from 'react'),尽管库内部正常,但这类代码会导致消费项目尝试加载React。

  • 目标项目的TS配置确保全局JSX源正确
    确认目标项目的tsconfig.json中,compilerOptions的jsxImportSource已设为vue,且jsx为preserve:

    {
      "compilerOptions": {
        "jsx": "preserve",
        "jsxImportSource": "vue"
      }
    }
    

这些配置调整后,消费项目会正确识别Vue JSX语法,不会再尝试寻找React依赖。

内容的提问来源于stack exchange,提问作者bhanu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:12:10