我想将我的 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”的第三方 Web 组件。所以他们都在
node_modules/@foo
。
我需要执行以下步骤:
告诉Vite所有以“foo-”开头的组件都是Web组件。
isCustomElement: (tag) => tag.startsWith('foo-')
添加“postcssLit”插件来帮助vite准备Web组件的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 prepare CSS for the webcomponents
postcssLit()
],
resolve: {
alias: {
// 3. Tell Vite how to treat CSS paths for webcomponents
'~@foo': fileURLToPath(new URL('./node_modules/@foo', import.meta.url))
}
}
});