TypeScript Vue项目用@vue/web-component-wrapper构建Web组件时装饰器解析报错咨询
问题场景
正在开发基于TypeScript的Vue项目,尝试使用@vue/web-component-wrapper将项目打包为Web组件,构建过程中出现语法解析报错。
项目相关代码
入口文件 main.ts
import JovoWebClientVue, { JovoWebClientVueConfig } from 'jovo-client-web-vue'; import Vue from 'vue'; import App from './App.vue'; import wrap from '@vue/web-component-wrapper'; Vue.config.productionTip = false; Vue.use<JovoWebClientVueConfig>(JovoWebClientVue, { /* 业务配置省略 */ }); // 常规开发模式的项目挂载逻辑 new Vue({ render: (h) => h(App), }).$mount('#app'); // 手动注册自定义元素的逻辑 const wrappedElement = wrap(Vue, App); window.customElements.define('v-card', wrappedElement);
根组件 App.vue
<template> <div id="app" class="w-screen h-screen"> <chat-widget /> </div> </template> <script lang="ts"> import ChatWidget from '@/components/ChatWidget.vue'; import { Component, Vue } from 'vue-property-decorator'; @Component({ components: { ChatWidget }, }) export default class App extends Vue {} </script> <style> @import 'assets/css/theme.pcss'; #app { -webkit-tap-highlight-color: transparent; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } </style>
执行的构建命令
vue build --target wc --name my-custom-element ./src/main.ts
构建报错信息
Module parse failed: Unexpected character '@' (11:0) You may need an additional loader to handle the result of these loaders. | import { Component, Vue } from 'vue-property-decorator'; | > @Component({ | components: { ChatWidget }, | })
解决方案
报错核心根因是构建流程未正确开启TypeScript装饰器语法的编译能力,webpack无法识别类声明上的@装饰器标记,按以下步骤调整即可:
- 开启TS编译的装饰器支持
打开项目根目录的tsconfig.json,确保compilerOptions中以下配置为开启状态:{ "compilerOptions": { "experimentalDecorators": true, "useDefineForClassFields": false } } - 修正Web组件构建的入口写法
Vue CLI 的--target wc构建模式已经内置了@vue/web-component-wrapper的包装逻辑,不需要在入口文件手动编写wrap()调用和customElements.define()注册逻辑。只需要在入口文件中直接导出要包装的根组件即可。
调整后适配wc构建模式的入口文件示例:import Vue from 'vue'; import App from './App.vue'; import JovoWebClientVue from 'jovo-client-web-vue'; Vue.config.productionTip = false; // 全局插件配置可正常保留 Vue.use(JovoWebClientVue, { /* 业务配置 */ }); // 直接导出根组件,Vue CLI 会自动完成组件包装、自定义元素注册流程 export default App; - 补充loader适配规则
若完成上述调整后仍报相同错误,可在vue.config.js中补充webpack规则,确保.ts文件的装饰器语法能被正常解析:module.exports = { chainWebpack: (config) => { config.module .rule('ts') .use('babel-loader') .loader('babel-loader'); }, };
内容的提问来源于stack exchange,提问作者GB5991
相关产品推荐
相关产品推荐

