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

无法在Vite项目中使用Stencil.js开发的blip-ds包

解决Stencil.js组件库blip-ds在Vite React项目中的兼容问题

1. 调整Vite配置适配组件库

Stencil输出的组件库代码结构和Vite默认的依赖优化逻辑存在冲突,需要修改vite.config.ts,让Vite正确处理该依赖:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react({
    // 允许React识别自定义元素标签(Stencil组件)
    babel: {
      plugins: [
        ['@babel/plugin-transform-react-jsx', {
          throwIfNamespace: false
        }]
      ]
    }
  })],
  optimizeDeps: {
    exclude: ['blip-ds'] // 禁止Vite自动优化该依赖,避免代码转译错误
  },
  ssr: {
    noExternal: ['blip-ds'] // 确保组件库代码不被外部化处理
  }
});

2. 正确初始化组件库

在项目入口文件(如main.tsx)中,按照Stencil的规范导入并初始化自定义元素:

import { applyPolyfills, defineCustomElements } from 'blip-ds/loader';

// 先加载必要的polyfill,再注册自定义元素
applyPolyfills().then(() => {
  defineCustomElements(window);
});

3. 适配React中Web Components的使用规则

在React组件中使用blip-ds组件时,注意两个关键点:

  • 自定义元素的属性需使用短横线命名(如variant="primary"而非variant="Primary")
  • 事件监听需通过ref结合addEventListener实现,而非React的onXXX语法

示例代码:

import { useRef, useEffect } from 'react';

function App() {
  const blipButtonRef = useRef<HTMLElement>(null);

  useEffect(() => {
    if (blipButtonRef.current) {
      blipButtonRef.current.addEventListener('click', () => {
        console.log('按钮被点击');
      });
    }
  }, []);

  return (
    <div className="App">
      <blip-button 
        ref={blipButtonRef} 
        label="测试按钮" 
        variant="primary"
      ></blip-button>
    </div>
  );
}

export default App;

4. 补充必要的Polyfill(可选)

如果需要兼容旧版浏览器,需安装并导入Stencil的polyfill:

npm install @stencil/core

在入口文件中添加:

import '@stencil/core/dist/polyfills/polyfills';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:52:20