【问题标题】:How to make Vue and Vite work with web components?如何让 Vue 和 Vite 与 Web 组件一起工作?
【发布时间】:2022-08-16 17:48:11
【问题描述】:

我想迁移我的Vue 2从 webpack 到 Vite 的项目。 并且必须使用使用lit-element 构建的第 3 方 Web 组件。

这些组件在运行时抛出错误(通过 vue):

未知的自定义元素:< foo-component > - 你注册了 组件正确吗?对于递归组件,请确保提供 “名称”选项。

还有(lit-element

未能在 \'ShadowRoot\' 上设置 \'adoptedStyleSheets\' 属性: 无法将值转换为 \'CSSStyleSheet\'。

据我所见,那些第 3 方 Web 组件仅在其索引文件中执行此操作(在 node_modules 内):

import FooComponent from \'./FooComponent\';
customElements.define(\'foo-component\', FooComponent);

所以在之前(使用 webpack 设置)我只是导入了它们,一切都可以正常工作。好吧,实际上对于 webpack,lit-scss-loader 也用于这些组件。

我假设 Vite 可能需要一些额外的配置,或者可能需要类似于 \"webpack\" 加载器的东西,但不确定我必须向哪个方向移动。

我做错了什么?

    标签: javascript vue.js vite custom-element lit


    【解决方案1】:

    配置 @vite/plugin-vue 以忽略 Lit 元素,例如,在其注册名称中以 my-lit 开头的元素:

    // vite.config.js
    import { defineConfig } from 'vite'
    
    export default defineConfig({
      plugins: [
        vue({
          template: {
            compilerOptions: {
              // treat all components starting with `my-lit` as custom elements
              isCustomElement: tag => tag.startsWith('my-lit'),
            },
          },
        }),
      ],
    })
    
    

    demo

    【讨论】:

      【解决方案2】:

      需要几个步骤。

      想象一下,我有名为“foo”的 3rd 方 Web 组件。所以他们都在node_modules/@foo

      我需要执行以下步骤:

      1. 告诉 Vite 所有以“foo-”开头的组件都是 webcomponents。

        isCustomElement: (tag) =&gt; tag.startsWith('foo-')

      2. 添加“postcssLit”插件,帮助 vite 为 webcomponents 准备 css。

      3. 告诉 Vite 如何威胁 web 组件的 css 路径。

        '~@foo': fileURLToPath(new URL('./node_modules/@foo', import.meta.url))

        这是完整的配置:

        //vite.config.ts
        
        import postcssLit from 'rollup-plugin-postcss-lit';
        
        export default defineConfig({
          plugins: [
            vue(
              {
                template: {
                  compilerOptions: {
                    // 1. Tell Vite that all components starting with "foo-" are webcomponents
                    isCustomElement: (tag) => tag.startsWith('foo-')
                  }
                }
              }
            ),
            vueJsx(),
            // 2. This "postcssLit" plugin helps to make css for the webcomponents
            postcssLit()
          ],
          resolve: {
            alias: {
              // 3. Tell to Vite how to threat css paths for webcomponents
              '~@foo': fileURLToPath(new URL('./node_modules/@foo', import.meta.url))
            }
          }
        });
        

      【讨论】:

        猜你喜欢
        • 2023-03-30
        • 1970-01-01
        • 2019-02-24
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        • 1970-01-01
        • 2012-02-29
        相关资源
        最近更新 更多