-
安装依赖
npm i vue-class-component vue-property-decorator -- save npm i ts -loader typescript tslint tslint-loader tslint-config-standard -D
初始化tsconfig
npx tsc --init
会自动生成 tsconfig.json (把"allowJs": true, 这个打开)允许文件中存在js,要不需要改太多东西
新增这些配置:
和compilerOptions 同级
"include" : [ "src/**/*.ts" , "src/**/*.tsx" , "src/**/*.vue" , "tests/**/*.ts" , "tests/**/*.tsx" ], // ts 排除的文件 "exclude": ["node_modules"]
vue.config.js
configureWebpack: {
resolve: { extensions: [ ".ts", ".tsx", ".js", ".json" ] },
module: {
rules: [
{
test: /\.ts$/ ,
exclude: /node_modules/ ,
enforce: 'pre' ,
loader: 'tslint-loader'
},
{
test: /\.tsx?$/ ,
loader: 'ts-loader' ,
exclude: /node_modules/ ,
options: {
appendTsSuffixTo: [ /\.vue$/ ],
}
}
]
}
},
新建ts解析.vue 在src目录下添加俩文件
shims-tsx.d.ts
// shims-tsx.d.ts src目录下
import Vue, { VNode } from 'vue' ;
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any;
}
}
}
shims-vue.d.ts
// shims-vue.d.ts src目录下
declare module '*.vue' {
import Vue from 'vue' ;
export default Vue;
}
// 为了typescript做的适配定义文件,因为.vue文件不是一个常规的文件类型,
// TypeScript是不能理解vue文件是干嘛的,加这一段是是告诉 TypeScript,vue文件是这种类型的。
// 没有这个文件,会发现 import 导入的所有.vue类型的文件都会报错。
// axios报错
declare module 'axios' {
interface AxiosInstance {
(config: AxiosRequestConfig): Promise <any>
}
}
添加tslint.json
{
"extends": "tslint-config-standard" ,
"globals" : {
"require": true
}
}
main.js改成main.ts 配置vue.config.js的入口为 main.ts
pages: {
index: {
entry: 'src/main.ts' ,
}
},
安装 @typescript-eslint/parser 将eslint校验改成 @typescript-eslint/parser
npm install @typescript-eslint/parser --save
更改.eslintrc.js
parserOptions: {
parser: '@typescript-eslint/parser'
},
-
查看更多关于原有vue项目支持typescript的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did223530