vue_ts ts环境搭建及ts格式写法

淩亂°似流年 2021-07-24 20:48 754阅读 0赞
  1. 1、搭建环境
  2. 方式一:
  3. vue ui手动配置->添加项目->手动配置
  4. ->添加BabelTypescript、使用配置文件,其他选择自定义
  5. ->选择css预处理器和Eslint
  6. 方式二:
  7. vue create 项目名创建
  8. 选择手动配置,可添加typescript
  9. 空格添加,回车下一步
  10. 方式三:手动创建
  11. (1)下载
  12. cnpm install -D vue 无需下载@types文件
  13. (2)编写vue声明文件,避免导入vue组件报错
  14. declare module '*.vue' {
  15. import Vue from 'vue'
  16. export default Vue 导出Vue构造器
  17. }
  18. (3)配置webpack
  19. const HtmlWebpackPlugin = require('html-webpack-plugin')
  20. const VueLoaderPlugin = require('vue-loader/lib/plugin')
  21. module.exports = {
  22. entry: {
  23. 'app': './src/index.ts'
  24. },
  25. output: {
  26. filename: '[name].[chunkhash:8].js'
  27. },
  28. resolve: {
  29. extensions: ['.js', '.ts', '.tsx', 'vue'],
  30. alias: {
  31. 'vue': 'vue/dist/vue.esm.js' 引入能解析template的完整es6版本
  32. }
  33. },
  34. module: {
  35. rules: [
  36. {
  37. test: /\.vue$/,
  38. loader: 'vue-loader'
  39. },
  40. {
  41. test: /\.tsx?$/,
  42. use: [{
  43. loader: 'ts-loader',
  44. options: {
  45. appendTsSuffixTo: [/\.vue$/] vue文件后面添加ts后缀
  46. }
  47. }],
  48. exclude: /node_modules/
  49. },
  50. {
  51. test: /\.css$/,
  52. use: [
  53. 'vue-style-loader',
  54. 'css-loader'
  55. ]
  56. }
  57. ]
  58. },
  59. plugins: [
  60. new HtmlWebpackPlugin({
  61. template: './src/tpl/index.html'
  62. }),
  63. new VueLoaderPlugin() 使用vue-loader需要添加插件
  64. ],
  65. optimization: {
  66. splitChunks: {
  67. chunks: 'all'
  68. }
  69. }
  70. }
  71. 2、类型约束
  72. (1)props参数约束:
  73. import Vue, { PropType } from 'vue'
  74. interface ComplexMessage {
  75. title: string,
  76. okMessage: string,
  77. cancelMessage: string
  78. }
  79. const Component = Vue.extend({
  80. props: {
  81. name: String, 可以直接写约束条件
  82. success: { type: String },
  83. callback: {
  84. type: Function as PropType<() => void> 可以通过PropType定义复杂类型约束条件
  85. },
  86. message: {
  87. type: Object as PropType<ComplexMessage>,
  88. required: true,
  89. validator (message: ComplexMessage) { 自定义验证规则
  90. return !!message.title;
  91. }
  92. }
  93. }
  94. })

发表评论

表情:
评论列表 (有 0 条评论,754人围观)

还没有评论,来说两句吧...

相关阅读

    相关 TS文件格式详解

    最近彻底研究分析了ts文件格式,这里做下学习总结: 简单的来说,ts文件中的信息其实就是通过负载类型字段来找,找到后把数据从负载中提取出来,ts中可以有很多媒体类型数据,比