首页 > 解决方案 > 如何将 Shoelace 组件库添加到现有的 Stencil.js 项目

问题描述

有一个名为“shoelace”(https://shoelace.style/getting-started/usage)的库,它是使用 stencil.js 构建的 Web 组件的集合。我想在我现有的 stencil.js 项目中使用该库中的组件。

但是,当我按照使用 NPM 进行本地安装的说明进行操作时,它不起作用,即使该组件似乎已加载。

尝试渲染鞋带的按钮组件时收到以下错误: Class constructor SlButton cannot be invoked without 'new'

这是我的test-button.tsx组件:

import { Component, h} from '@stencil/core';

import '@shoelace-style/shoelace/dist/themes/base.css';

import SlButton from '@shoelace-style/shoelace/dist/components/button/button';


@Component({
  tag: 'test-button',
  shadow: true,
})

export class TestButton {

  render() {

    return (
      <div>
        <SlButton>hdcsddsy</SlButton>
      </div>
    );
  }
}

这里有什么问题?

标签: typescriptimportweb-componentstenciljsshoelace

解决方案


鞋带不再使用 Stencil 开发。从 beta.29 开始,它使用Lit。但是,最终结果仍然是自定义元素的集合,因此您可以在任何地方使用它们。

首先,安装鞋带:

npm i @shoelace-style/shoelace 

然后,在您的 Stencil 组件中,导入您要使用的 Shoelace 元素,如下所示:

import '@shoelace-style/shoelace/dist/components/button/button';

自定义元素通过副作用注册。要在 JSX 中使用它们,请使用相应的 HTML 标记:

render() {
  return <sl-button type="primary">Click me!</sl-button>;
}

注意:如果您没有看到任何样式,您还需要加载浅色或深色主题


推荐阅读