Electron+Vue3+TypeScript项目编译失败:解析器配置问题求助
Vue 3 + TypeScript + Electron 项目搭建报错解决方案
问题描述
已通过以下命令成功运行Electron+Vue3项目:
vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve
但将组件中的<script>改为<script lang="ts">后,应用崩溃,提示Parsing error: No Babel config file detected。
尝试过的排查步骤:
- 安装
babel-eslint、@babel/core、@babel/eslint-parser并创建.eslintrc.js,出现Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc.js': Cannot find module '@typescript-eslint/parser'错误; - 安装
@typescript-eslint/eslint-plugin、@typescript-eslint/parser等依赖后,出现字符串未终止、模板代码不兼容等异常; - 参考官方指南、移动项目目录等操作均无效。
当前.eslintrc.js配置:
module.exports = { plugins: ["@typescript-eslint/eslint-plugin"], parserOptions: { parser: "@typescript-eslint/parser", sourceType: "module", ecmaVersion: 8, extraFileExtensions: ['.vue'], ecmaFeatures: { jsx: true } }, extends: [ 'plugin:@typescript-eslint/eslint-recommended' ], overrides: [{ files: ['*.ts', '*.tsx'], rules: { 'no-unused-vars': 'off', } }] }
核心报错:解析器无法识别Vue模板、TS语法解析失败,即使是简单的<template><div> hey </div></template>也触发错误。
解决方案
方案一:修复现有项目
- 安装完整的TS兼容依赖
npm install -D typescript @vue/eslint-config-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-vue
- 替换
.eslintrc.js配置,确保Vue与TS解析兼容
module.exports = { root: true, env: { node: true, electron: true }, extends: [ 'plugin:vue/vue3-essential', 'eslint:recommended', '@vue/typescript/recommended' ], parserOptions: { ecmaVersion: 2020 }, rules: { 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': ['warn'] } }
- 添加
tsconfig.json(若项目中无此文件)
{ "compilerOptions": { "target": "esnext", "module": "esnext", "strict": true, "jsx": "preserve", "moduleResolution": "node", "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "useDefineForClassFields": true, "sourceMap": true, "baseUrl": ".", "types": [ "node", "electron" ], "paths": { "@/*": [ "src/*" ] }, "lib": [ "esnext", "dom", "dom.iterable", "scripthost" ] }, "include": [ "src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue" ], "exclude": [ "node_modules" ] }
- 调整Vue组件的TS写法,推荐使用setup语法糖
<script lang="ts" setup> const msg: string = 'Hello Vue 3 + TypeScript + Electron' </script> <template> <div>{{ msg }}</div> </template>
- 重启项目
npm run electron:serve
方案二:重新搭建项目(更简便)
直接通过Vue CLI创建自带TS的项目,再集成Electron,避免手动配置的兼容问题:
- 创建Vue3+TypeScript项目
vue create app_name
创建时选择Manually select features,勾选TypeScript、Vue 3.x等所需选项。
2. 进入项目目录,添加Electron builder
cd app_name vue add electron-builder
- 启动项目
npm run electron:serve
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

