经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
vue项目引入ts步骤(小结)
来源:jb51  时间:2019/10/31 15:00:08  对本文有异议

最近考虑到老项目代码的可维护性以及稳定性,决定引入ts做规范检测。因为介绍的东西比较基础,如果介绍的不对,麻烦指正。

1. 简介

TypeScript 是 JavaScript 的一个超集,主要提供了类型系统和对 ES6 的支持。网上关于ts的学习资料很多,这里不做详细介绍。可参考的学习网站:

ts.xcatliu.com/

typescript.bootcss.com/

2. 安装依赖包

  1. cnpm i typescript ts-loader --save-dev

3. 添加tsconfig.json文件

在项目根目录下添加 tsconfig.json 文件。tsconfig.json 文件用来指定ts的编译选项。配置可参考:

https://typescript.bootcss.com/tsconfig-json.html

项目工程 tsconfig.json 文件配置如下:(仅做参考)

  1. {
  2. "compilerOptions": {
  3. "baseUrl": ".",
  4. "experimentalDecorators": true,
  5. "emitDecoratorMetadata": true,
  6. "noEmitOnError": true,
  7. "target": "esnext",
  8. "module": "esnext",
  9. "strict": true,
  10. "allowJs": true,
  11. "noEmit": false,
  12. "noImplicitThis": true,
  13. "esModuleInterop": true,
  14. "sourceMap": true,
  15. "moduleResolution": "node"
  16. },
  17. "include": [
  18. "src/**/*", "types"
  19. ],
  20. "exclude": [
  21. "node_modules",
  22. "build"
  23. ]
  24. }
  25.  

4. webpack打包配置修改

webpack.config.js 打包文件修改,新增对.ts文件的打包配置。

4.1 入口文件后缀名由.js修改为.ts

  1. module.exports = {
  2. entry: {
  3. app: ['@babel/polyfill', './src/main.ts']
  4. }
  5. }

4.2 extensions 文件扩展名增加 .ts, .tsx 文件的支持

tsx针对react项目文件的支持,因为我们的工程基于vue开发,支持.ts文件就可以了。

  1. module.exports = {
  2. resolve: {
  3. extensions: ['.js', '.vue', '.json', '.css', '.ts']
  4. }
  5. }
  6.  

4.3 loader增加对ts文件的支持

使用ts-loader来转换ts文件。

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.ts?$/,
  6. loader: 'ts-loader',
  7. exclude: /node_modules/,
  8. options: {
  9. appendTsSuffixTo: [/\.vue$/],
  10. }
  11. }
  12. ]
  13. }
  14. }
  15.  

5. eslint 添加对ts文件的检测

5.1 安装依赖包

  1. cnpm i @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-typescript eslint-plugin-typescript --save-dev
  2.  

@typescript-eslint/parser ts文件解析器

@typescript-eslint/eslint-plugin 版本号需要与@typescript-eslint/parser的版本一致,解析器相关的配置选项

eslint-config-typescript 针对ts项目配置的eslint检测规范

5.2 .eslintrc配置文件修改

.eslintrc配置文件修改,支持对ts的文件的校验。经过多次调整,我们工程的 .eslintrc 配置文件如下:

  1. {
  2. "parserOptions": {
  3. "parser": "@typescript-eslint/parser",
  4. "project": "./tsconfig.json",
  5. "extraFileExtensions": [".vue"],
  6. "ecmaVersion": 2017,
  7. "sourceType": "module",
  8. "ecmaFeatures": {
  9. "modules": true
  10. }
  11. },
  12. "env": {
  13. "jest": true,
  14. "browser": true
  15. },
  16. "settings": {
  17. "import/resolver": {
  18. "node": {
  19. "extensions": [".js", ".jsx", ".ts", ".tsx", ".eslintrc"]
  20. },
  21. "webpack": {
  22. "config": {
  23. "resolve": {
  24. "alias": {
  25. "src": "src"
  26. }
  27. }
  28. }
  29. }
  30. }
  31. },
  32. "plugins": [
  33. "vue",
  34. "babel",
  35. "@typescript-eslint"
  36. ],
  37. "extends": [
  38. "eslint:recommended",
  39. "plugin:vue/base",
  40. "typescript",
  41. "standard"
  42. ],
  43. "rules": {
  44. "func-names": 0,
  45. "one-var": [1, "never"],
  46. "prefer-const": 1,
  47. "no-unused-expressions": 1,
  48. "new-cap": 2,
  49. "prefer-arrow-callback": 2,
  50. "arrow-body-style": 0,
  51. "max-len": [
  52. 1,
  53. {
  54. "code": 200,
  55. "ignoreStrings": true,
  56. "ignoreUrls": true,
  57. "ignoreRegExpLiterals": true
  58. }
  59. ],
  60. "consistent-return": "off",
  61. "default-case": 2,
  62. "prefer-rest-params": 2,
  63. "no-script-url": 0,
  64. "no-console": [
  65. 2,
  66. {
  67. "allow": ["info", "error", "warn", "log"]
  68. }
  69. ],
  70. "no-duplicate-imports": 2,
  71. "newline-per-chained-call": 2,
  72. "no-underscore-dangle": 2,
  73. "eol-last": 2,
  74. "no-useless-rename": 2,
  75. "class-methods-use-this": 0,
  76. "prefer-destructuring": 0,
  77. "no-unused-vars": 0,
  78. "@typescript-eslint/no-unused-vars": 1,
  79. "no-plusplus": 0,
  80. "import/prefer-default-export": 0,
  81. "import/no-dynamic-require": 2,
  82. "@typescript-eslint/no-var-requires": 2,
  83. "no-use-before-define": [
  84. "error",
  85. {
  86. "functions": false
  87. }
  88. ],
  89. "@typescript-eslint/no-use-before-define": 0,
  90. "@typescript-eslint/explicit-function-return-type": 0,
  91. "@typescript-eslint/interface-name-prefix": 0,
  92. "no-invalid-this": 0,
  93. "babel/no-invalid-this": 2,
  94. "no-await-in-loop": "off",
  95. "array-callback-return": "off",
  96. "no-restricted-syntax": "off",
  97. "@typescript-eslint/no-explicit-any": 0,
  98. "import/no-extraneous-dependencies": 0,
  99. "import/no-unresolved": 0,
  100. "@typescript-eslint/explicit-member-accessibility": 0,
  101. "@typescript-eslint/no-object-literal-type-assertion": 0,
  102. "no-param-reassign": [
  103. 2,
  104. {
  105. "props": false
  106. }
  107. ],
  108. "generator-star-spacing": "off",
  109. "indent": [2, 4, {
  110. "SwitchCase": 1
  111. }],
  112. "eqeqeq": 0,
  113. "no-else-return": 2,
  114. "arrow-parens": 0,
  115. "space-before-function-paren": ["error", "never"],
  116. "comma-dangle": [2, "never"],
  117. "semi": [2, "always"]
  118. }
  119. }
  120.  

注意"extends": ["plugin:vue/base"], 只能选择vue/base,不能用vue/recommend。不然会有规则冲突。

6. 项目文件转换

项目配置好后,开始对老代码进行改造,来支持ts的语法检测。

6.1 增加ts声明文件目录

项目中总会依赖一些资源包,或是自己开发的一些组件,这些文件需要补充声明文件,声明文件就是将多个声明语句放在一起,这些声明文件可统一放到一个目录里。这个目录需要包含在 tsconfig.json 文件的include里。

ms工程在根目录下新建 types 目录,目前包含 vue.d.ts, request.d.ts, dialog.d.ts, base.d.ts 等文件。

6.2 全局vue.d.ts声明文件

需要在ts环境下识别vue文件,需要添加 vue.d.ts 全局声明文件,例子如下:

  1. import VueRouter, { Route } from 'vue-router';
  2. import RequestAxios from './request';
  3.  
  4. declare module '*.vue' {
  5. import Vue from 'vue';
  6. export default Vue;
  7. }
  8. declare module 'vue/types/vue' {
  9. interface Vue {
  10. $router: VueRouter;
  11. $route: Route;
  12. $request: RequestAxios;
  13. ....
  14. }
  15. }
  16.  

6.2 vue文件的改造

vue文件的改造,只改造js部分,代码大致修改如下:

  1. import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
  2.  
  3. @Component({
  4. components: {
  5. ....
  6. }
  7. })
  8. export default class MyComponent extends Vue {
  9. // prop
  10. @Prop({ default: () => {} }) readonly pageInfo !: any
  11.  
  12. // data
  13. private showAnimation : boolean = true;
  14.  
  15. // watch
  16. @Watch('showModuleIndex')
  17. onShowModuleIndexChanged(newValue: any) {
  18. this.$emit('input', newValue);
  19. }
  20.  
  21. // computed
  22. get list() {
  23. const { page, cityList } = this;
  24. return page.cityList.split(',').map(
  25. cityId => cityList.find(c => String(c.id) === cityId)
  26. );
  27. }
  28.  
  29. // mounted
  30. private mounted() :void {
  31. this.initEditor();
  32. }
  33.  
  34. // methods
  35. private initEditor() :void {
  36. ....
  37. }
  38. }
  39. </script>
  40.  

6.3 js文件的改造

将文件后缀名更改为.ts,然后加上类型就可以了。

7. 踩坑总结

大部分都是eslint校验时的报错,按照提示修复就可以了。

"vue/html-indent": [2, 4] eslint这条规则去掉

"plugin:vue/base"与"plugin:vue/recommend"的区别

...

8. 总结

项目改造过程中,大部分时间都是在查配置兼容问题,配置这块解决了,改造起来速度还是挺快的。虽然前期会有一些改造成本,但是长远来看,还是有意义的。毕竟很多代码类型上的问题在开发阶段就可以暴露,不用等到运行时才发现了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号