[英]How to make Vue and Vite work with web components?
我想将我的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”加载器的东西,但不确定我必须向哪个方向移动。
我做错了什么?
配置@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'),
},
},
}),
],
})
需要几个步骤。
想象一下,我有名为“foo”的 3rd 方 Web 组件。 所以它们都在node_modules/@foo
中。
我需要执行以下步骤:
告诉 Vite 所有以“foo-”开头的组件都是 webcomponents。
isCustomElement: (tag) => tag.startsWith('foo-')
添加“ postcssLit ”插件帮助vite为webcomponents准备css。
告诉 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))
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.