前言
如果原有项目 webpack 版本低于 4 ,建议直接用 vue-cli 新建项目然后把项目文件迁移过去
原有项目添加 TypeScript
-
添加 TypeScript 及代码检查
npm install typescript ts-loader tslint tslint-loader -D
-
初始化 TypeScript 及代码检查配置
详细配置- TypeScript
- Tslint
- 注: 推荐使用 Eslint 进行代码检查,这里是因为我操作的项目eslint 版本较低不支持 ts 代码检查
./node_modules/.bin/tsc --init ./node_modules/.bin/eslint --init
-
修改 webpack 配置 添加 .ts .tsx 用于搜索 ts 文件的扩展名
resolve: { extensions: ['.ts', '.tsx', '.js', '.vue', '.json'] }
对于 ts 文件添加 loader 配置
{ // 加入对文件的ts识别 test: /.ts$/, enforce: 'pre', loader: 'tslint-loader' }, { test: /.tsx?$/, loader: 'ts-loader', options: { appendTsSuffixTo: [/.vue$/], } },
-
添加 vue 对 ts 的支持
npm install vue-property-decorator vue-class-component -S
-
改造 vue 文件
只需要在 script 标签加上 lang="ts" 并且引入 vue-property-decorator具体用法参考 vue-property-decorator 在 npm 的介绍以及TypeScript文档
新项目添加 TypeScript
如果项目是vue-cli创建的可以直接使用vue add @vue/typescript 添加,具体可参考vue typescript 插件
-
安装 vue-cli,已有 vue 脚手架 可以忽略直接进行下一步 安装:
npm install -g @vue/cli # OR yarn global add @vue/cli
-
创建一个项目
vue create my-project
-
选择自定义配置
-
选中 TypeScript
-
选择代码风格格式化检测工具
-
等待完成
-
同样的具体用法
参考 vue-property-decorator 在 npm 的介绍以及TypeScript文档