vuejs/create-vue 不支持 JSX,即使你选择了 "Add JSX Support"



我使用此处编写的create-vue命令创建了新的Vue项目。以下是我对问题的回答:

D:checks>npm init vue@latest
Vue.js - The Progressive JavaScript Framework
√ Project name: ... VueQuestionJSX
√ Package name: ... vuequestionjsx
√ Add TypeScript? ... No
√ Add JSX Support? ... Yes
√ Add Vue Router for Single Page Application development? ... Yes
√ Add Pinia for state management? ... Yes
√ Add Vitest for Unit Testing? ... Yes
√ Add Cypress for End-to-End testing? ... Yes
√ Add ESLint for code quality? ... Yes
√ Add Prettier for code formatting? ... Yes
Scaffolding project in D:checksVueQuestionJSX...
Done. Now run

我没有更改项目中的任何设置。我刚刚在script中添加了简单的JSX变量

const textDiv = <div>Hi all!</div>;

并决定检查一下它是如何工作的。它没有。首先,ESlint显示了一个错误Parsing error: Unexpected token <。然后编译器抛出错误

[vite] Internal server error: Failed to parse source for import analysis because the content
contains invalid JS syntax. Install @vitejs/plugin-vue to handle .vue files.
Plugin: vite:import-analysis

我查看了@vitejs/plugin-vue-jsx的自述文件,发现它似乎不理解这种常见的语法。首先必须导出包含JSX的组件,其次必须使用defineComponent函数
我创建了一个单独的文件CheckJSX.vue。以下是其全部内容:

CheckJSX.js

import { defineComponent } from "vue";
const Bar = defineComponent({
render() {
return <div>Test</div>;
},
});
export { Bar };

defineComponent返回Vue时,组件I插入Bar作为组件

主页视图.vue

<script setup>
import { Bar } from "@/components/CheckJSX.js";
</script>
<template>
<Bar />
</template>

ESlint对这种语法感到震惊,并用红色突出显示了所有内容。可能它不喜欢.vue扩展。我把它改成了.js。ESLint冷静下来,但仍然显示错误Parsing error: Unexpected token <
编译器抛出错误

20:56:29 [vite] Internal server error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
Plugin: vite:import-analysis
File: D:/checks/VueQuestionJSX/src/components/CheckJSX.js
4  |    render() {
5  |      return <div>Test</div>;
6  |    },
|     ^
7  |  });

为什么Vue不理解开箱即用的JSX,即使你选择了";添加JSX支持">

解决方法是在ESLint-config:中启用JSX解析

// .eslintrc.cjs
module.exports = {
⋮
"parserOptions": {
⋮
"ecmaFeatures": {
"jsx": true,
}
}
}

我认为这是一个新的bug,因为JSX以前在一个新搭建的项目中为我开箱即用。我建议提交一个GitHub问题来修复它。

最新更新