前言
因为最近公司的团队热衷于vue框架,新项目想着练练typescript,于是开始了vue+ts的踩坑之路…本文意在为和我有一样想法的伙伴们省去踩坑的时间,下面话不多说了,来一起看看关于Vue2 Vue-cli中利用Typescript需要的配置是什么吧。
一、初步配置
首先安装官方插件vue-class-component,vue-property-decorator,配置webpack。
webpack配置如下:
修改入口文件
entry: {
app: './src/main.ts'
}resolve部分:
extensions: ['.js', '.vue', '.json', '.ts', '.tsx']配置loader
{
test: /.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/.vue$/],
}
}配置tsconfig.json
{
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
],
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"allowJs": true,
"module": "es2015",
"target": "es5",
"moduleResolution": "node",
"experimentalDecorators": true,
"isolatedModules": true,
"lib": [
"dom",
"es5",
"es2015.promise"
],
"sourceMap": true,
"pretty": true
}
}二、实战!
配好配置只是第一步,在项目里跑起来才是王道。
在vue文件的script标签里添加
lang='ts'因为ts-loader不像配过loader的webpack一样知道vue,html等文件是什么东西,你跑起来后会报模块无法解析的错误,所以还需要配置.d.ts声明文件
vue的如下配置
declare module "*.vue" {
import Vue from 'vue';
export default Vue;
}你也可以为其它的非js模块配置.d.ts文件如html(告诉ts-loader把html理解成字符串)
declare module "*.html" {
let template: string;
export default template;
}配置好之后ts就能理解这些模块了
从vue-property-decorator引入需要用到的模块
(一般只用到Component, Vue, Watch, Prop这四个,其它3个没用到也没研究,知道的大佬可以解释下。)
import { Component, Vue, Watch } from 'vue-property-decorator'这里拿之前写的sidbar的代码当个栗子:
class HoverTopElem {
leaveTop: number = -200
top: number = null
height: number = null show(e) {
this.top = e.target.getBoundingClientRect().top
this.height = e.target.clientHeight










