进阶:Vue----Vue—TypeScript
一.TypeScript 配置
1.安装插件
npm install --save typescript ts-loader @types/node vue-class-component
2.Webpack
在Webpack的module.rules
里面添加对ts的支持(我这里的webpack版本是2.x):
{ test: /\.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { test: /\.tsx?$/, exclude: /node_modules/, use: [ "babel-loader", { loader: "ts-loader", options: { appendTsxSuffixTo: [/\.vue$/] } } ] }
3.tsconfig.json
创建tsconfig.json文件,放在根目录下,和package.json
同级
配置内容主要也看个人需求,具体可以去typescript的官网查看,但是有一点需要注意:
在Vue中,你需要引入 strict: true (或者至少 noImplicitThis: true,这是 strict 模式的一部分) 以利用组件方法中 this 的类型检查,否则它会始终被看作 any 类型。
这里列出我的配置,功能在注释中给出
{ "include": [ "src/*", "src/**/*" ], "exclude": [ "node_modules" ], "compilerOptions": { // types option has been previously configured "types": [ // add node as an option "node" ], // typeRoots option has been previously configured "typeRoots": [ // add path to @types "node_modules/@types" ], // 以严格模式解析 "strict": true, // 在.tsx文件里支持JSX "jsx": "preserve", // 使用的JSX工厂函数 "jsxFactory": "h", // 允许从没有设置默认导出的模块中默认导入 "allowSyntheticDefaultImports": true, // 启用装饰器 "experimentalDecorators": true, "strictFunctionTypes": false, // 允许编译javascript文件 "allowJs": true, // 采用的模块系统 "module": "esnext", // 编译输出目标 ES 版本 "target": "es5", // 如何处理模块 "moduleResolution": "node", // 在表达式和声明上有隐含的any类型时报错 "noImplicitAny": true, "lib": [ "dom", "es5", "es6", "es7", "es2015.promise" ], "sourceMap": true, "pretty": true } }
4.修改main.js
- 把项目主文件
main.js
修改成main.ts
,里面的写法基本不变,但是有一点需要注意: 引入Vue文件的时候需要加上.vue
后缀,否则编辑器识别不到 - 把webpack的entry文件也修改成
main.ts
5.vue-shims.d.ts
TypeScript并不支持Vue文件,所以需要告诉TypeScript*.vue
文件交给vue编辑器来处理。解决方案就是在创建一个vue-shims.d.ts文件,建议放在src目录下再创建一个typings
文件夹,把这个声明文件放进去,如:src/typings/vue-shims.d.ts
,文件内容:
*.d.ts
类型文件不需要手动引入,TypeScript会自动加载
declare module '*.vue' { import Vue from 'vue' export default Vue }
到这里TypeScript在Vue中配置就完成了