原创

vue3直接套用elementplus官方文档里模版报错解决

温馨提示:
本文最后更新于 2022年11月19日,已超过 495 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

具体错误

直接套用elementplus官方文档里的模版,报错
Module parse failed: Unexpected token……You may need an additional loader to handle the result of these loaders.

简单来说就是elementplus我能用,用不了的是它写了ts语法的地方。

这该死的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

2.引入Typescript包

npm install --save-dev typescript
npm install --save-dev ts-loader<br/>

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,该文件里面什么都不用写。因为有了tsconfig.json后,编辑器会自动在includeexclude包含的范围中查找ts文件,如果找不到ts文件就会报错,当在includeexclude范围中添加了ts文件,编辑器就不会报错了。

到这里重新编译运行,组件正常显示并且功能正常!问题解决!

正文到此结束
该篇文章的评论功能已被站长关闭
本文目录