美文网首页
vscode+vue3+typescript系列问题

vscode+vue3+typescript系列问题

作者: taiyosen | 来源:发表于2022-08-15 15:20 被阅读0次

环境

  • Win10
  • VS code: 1.70.1
  • vue: ^3.2.33

问题汇总

Vetur or Volar

原来用VS code写vue3好好的,不知道哪天升级了什么(估计是vetur插件),打开xx.vue就是一片醒目的红色警告,右下角可以看到弹窗提示

image.png
原因是因为vetur默认在工作空间根目录查找这两个文件,而我是一个monirepo,根据官方文档,可以创建一个vetur.config.js来配置多个子项目的目录,具体查看官方文档:
https://vuejs.github.io/vetur/guide/setup.html#advanced

增加了配置后,打开vue文件,发现template/script全是一大片的红色波浪线,鼠标移上去会发现全是vetur的错误提示,查了一下vue官网:
https://cn.vuejs.org/guide/typescript/overview.html#ide-support
其中有一段文字:

TIP

Volar 取代了我们之前为 Vue 2 提供的官方 VSCode 扩展 Vetur。如果你之前已经安装了 Vetur,请确保在 Vue 3 的项目中禁用它。

于是把vetur扩展卸了,安装Volar。

EsLint

波浪线少了些,但是还有:

image.png
这很明显应该是eslint配置有问题。
这里有人给出解决方案:
https://stackoverflow.com/questions/66597732/eslint-vue-3-parsing-error-expected-eslint
原本我的eslintrc.js中的配置:
{
    // ...
    'parser': '@typescript-eslint/parser',
    'parserOptions': {
        'ecmaVersion': 'latest',
        'sourceType': 'module'
    }
}

修改为

{
    // ...
    'parser': 'vue-eslint-parser',
    'parserOptions': {
        'parser': '@typescript-eslint/parser',
        'ecmaVersion': 'latest',
        'sourceType': 'module'
    }
}

关于vue-eslint-parser的更多配置:https://www.npmjs.com/package/vue-eslint-parser
vscode中eslint的output还有如下错误信息:

[Info  - 10:41:25] ESLint server is starting
[Info  - 10:41:26] ESLint server running in node v16.13.2
[Info  - 10:41:26] ESLint server is running.
[Info  - 10:41:29] ESLint library loaded from: F:\tgit\smarttalk\app\chartknowscli\node_modules\eslint\lib\api.js
[Info  - 11:41:18] 
Failed to load the ESLint library for the document f:\tgit\smarttalk\tools\spider\typings\datacenter.d.ts

我的eslintrc.js配置文件位于F:\tgit\smarttalk\app\chartknowscli目录下,这也是vue3+typescript项目所在,它引用到另一个项目f:\tgit\smarttalk\tools\spider中的类型文件,根据eslint的提示,这种情况需要全局安装eslint:npm i eslint -g,安装后重启vscode即可。

<> 操作符

如下图所示,当我在vue文件的<script>中括号中使用了typescript的<> operator时,会有这样的错误。明显ts将其视为JSX,认为我应该写<keyof></keyof>

image.png
image.png

也有人提出类似的问题:
https://stackoverflow.com/questions/58392378/typescript-type-cast
对此别无他法,只能改用as类型转换关键字。

'module' is not defined.eslint

.eslintrc.js中提示'module' is not defined.eslint

image.png
原因是在执行npm init @eslint/config时选择的是browser环境,而实际上我是一个vue应用,改成
'env': {
    'node': true,
    'es2021': true
}

ESLint: Cannot read properties of undefined (reading 'loc') Occurred while linting xxx

每次一写const,右下角马上弹出

image.png
原因是没使用@typescript-eslint/indent插件,把indent换成@typescript-eslint/indent即可。
-       'indent': [
+       '@typescript-eslint/indent': [
            'error',
            4
        ],

Cannot find name 'uni'.ts(2304)

在tsconfig.json中已经配置了"types": ["@dcloudio/types"],按道理uni应该作为全局变量被导入了,但依旧报错,看uniapp论坛有人说是Volar升级后冲突了。
https://ask.dcloud.net.cn/question/149424

相关文章

网友评论

      本文标题:vscode+vue3+typescript系列问题

      本文链接:https://www.haomeiwen.com/subject/zbrlgrtx.html