0


vue3引用ElementPlus出错|如何在vue中引用TypeScript

具体错误:直接套用elementplus官方文档里的模版,报错:

Module parse failed: Unexpected token……You may need an additional loader to handle the result of these loaders.

简单来说就是elementplus我能用,用不了的是它写了ts语法的地方,这个很关键,如果你连基本的elementplus都用不了,那么这篇博客不适合你哦,可以参考我的这篇博客:

http://t.csdn.cn/fgD4Ohttp://t.csdn.cn/fgD4O这该死的bug改了一天,查遍全网博客,终于让我琢磨出来了!很无语的是怎么就没有一篇是适合我的。。浅记一下,或许能帮到遇到的问题和我一样的大冤种😭


我尝试了以下办法,都是失败告终:

1.将<script lang="ts" setup> 中的lang="ts"去掉

❌不行,治标不治本,会导致ts语法用不了(vue文件中),如import type { FormInstance, FormRules } from 'element-plus'就会报错,这样子你后面的很多方法都实现不了

2.更有甚者,直接自暴自弃,将用到FormInstance, FormRules的地方全部删掉,那么这用element还有啥用?不如直接写html好吧。

3.去改某处 webpack.config.js的配置。现在想想真的很傻,vue3的配置是在vue.config.js里啊,就在很显眼的根目录下,改他就得了呀非要费尽心机去找 webpack.config.js。。


解决办法

1.配置Vue-Loader

npm install -D vue-loader vue-template-compiler

Why:

想了解更多的请移步官方文档https://vue-loader.vuejs.org/zh/#vue-loader-%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9Fhttps://vue-loader.vuejs.org/zh/#vue-loader-%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F


2.引入Typescript包

npm install --save-dev typescript
npm install --save-dev ts-loader

3.修改vue.config.js

vue页面该咋写还是咋写,一点不用改。

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true
})
module.exports = { configureWebpack: {
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"],  
     alias: {}
  },
  module: {        
    rules: [    
      {    
        test: /\.tsx?$/,    
        loader: 'ts-loader',    
        exclude: /node_modules/,    
        options: {
          appendTsSuffixTo: [/\.vue$/],    
        }    
      }        
    ]    
  }    
}
}

4.根目录下创建tsconfig.json

代码如下:

{
    "compilerOptions": {
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true,
      "lib": ["dom","es2016"],
      "target": "es5"
    },
    "include": ["./src/**/*"]  
}

5.创建ts文件

src目录下创建一个ts文件,如test.ts,该文件里面什么都不用写。Why?

因为有了

tsconfig.json

后,

VScode

会自动在

include

exclude

包含的范围中查找ts文件,如果找不到ts文件就会报错,当在

include

exclude

范围中添加了ts文件,

VScode

就不会报错了。

没写报错:[tsl] ERROR TS18003: No inputs were found in config file 'tsconfig.json'. Specified 'include'

Over!!

重新编译运行,组件正常显示并且功能正常!问题解决啦!制作不易,欢迎点赞收藏哦!

标签: vue.js webpack vscode

本文转载自: https://blog.csdn.net/weixin_46019681/article/details/124953663
版权归原作者 今天又有什么bug 所有, 如有侵权,请联系我们删除。

“vue3引用ElementPlus出错|如何在vue中引用TypeScript”的评论:

还没有评论