文章目录
问题背景
在做+ElementPlus项目时,复制粘贴ElementPlus定制网站官网的代码到项目中,定制网站结果会报这样的错:
Parsing error: Unexpected token
定制网站明明就是按照官网的代码原封不动的粘贴过来,为什么会报错呢?经过排查,原来是< script>标签中加了“lang = ts”,也就是使用了语法糖。导致出现这个错误
问题解决
步骤一:下载typescript和ts-loader
npm install typescript ts-loader --save-dev
- 1
步骤二:配置vue.config.js文件,添加下面的代码
configureWebpack: { resolve: { extensions: [".ts", ".tsx", ".js", ".json"] }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: [/\.vue$/], } } ] } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
添加好后,vue.config.js 内容如下:
const { defineConfig } = require('@vue/cli-service')module.exports = defineConfig({ transpileDependencies: true, configureWebpack: { resolve: { extensions: [".ts", ".tsx", ".js", ".json"] }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: [/\.vue$/], } } ] } }})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
步骤三:新建tsconfig.json文件放在项目根目录,并添加如下内容
{ "compilerOptions": { "target": "es5", "module": "commonjs", "strict": true, "strictNullChecks": true, "esModuleInterop": true, "experimentalDecorators": true }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
步骤四:在src根目录下新建vue-shim.d.ts文件,并添加如下内容;( 这个文件可以让vue识别ts文件,不加会报错)
declare module "*.vue" { import Vue from "vue"; export default Vue;}
- 1
- 2
- 3
- 4
步骤五:重启项目,成功运行
本文主要参考如下文章: