TS基础-----------get新技能

ts 优点: 利于维护

typescript runoob 教程—> 点击跳转

定义一个 .ts的文件 ts在浏览器上 是不能够直接执行的 需要转是、js 简单的发方法就是 cd ./当前ts路径 使用tsc xxx.ts 就会生成当前的js文件

ts语法基础知识



//字符串
let str:string="aaa"


//数组
let arr :Array<number>=[1,2,3]
let arr1:string[]=["a","b","c"]

//undefined ,null
let  _undefined:undefined=undefined
let  _null  :null=null



// ts中的或
let  some_var : number|string|boolean=123
     some_var : 'AAA';





// 任意类型
let any_var :any =123;////函数没有返回值  return     类型属于 void
function func(ary:number):void{

}
func(111)


function func2(ary:string):boolean{
    //代码
    // ...
    // 如果是boolean类型  要return一个不布尔值
    return true

}



 
// 对象  使用接口来定义对象的类型  要统一对应缺一不 可否则报错
interface Iperson{
    name: string;
    age : number;
    sex : string;
}

let obj : Iperson={
    name :"张三",
    age : 20,
    sex : "男"
}

//直接定义空对象  会报错-------------

// let  boj2: Iperson={}


//对象可选项 不写不会报错------------

interface Iperson2{
    name?: string;
    age : number;
    sex : string;
}
let obj2 : Iperson2={
  
    age : 20,
    sex : "男"
}


//接口继承--------------
interface IA extends Iperson2{
    hobby:Array<string>;
}
let obgIA: IA={
    name :"张三",
    age : 20,
    sex : "男",
    hobby:['a','a']
}


//继承多个-------------
interface IB {
    name :string

}
interface IC{
    age:number

}
interface ID extends IB,IC{
    sex:string

}

let  obj3:ID={
    name :"张三",
    age : 20,
    sex : "男",
}


//ts 中的与------------
let person1: IB & IC ={
    name :"张三",
    age : 20,
}




// --------------------------
interface Iperson3{
    name?:string;
    age?:number;
    [propName:string]: any
}

let person3:Iperson3={} //不报错
let person4:Iperson3={//不报错
    a:1
} 


// implements接口实现
interface Iperson4{
    name:string;
    age:number;
    sex:string;
    getName:()=>string;
    getAge ():number;
}
class Person implements Iperson4{
    //继承的都要拿过来写
    name:string="张三";
    age:number=20;
    sex:string;
    getName():string{
        return this.name
    };
    getAge ():number{
        return this.age
    };

    //还可以写自己的方法
    sayHellow():void{

    }
}


//类型断言
function getLength(str:number|string):number{
    if((str as string).length){
        return (str as string).length
    }else{
        return str.toString().length
    }

}

//非空断言
function func3(arg?:string):number{
    return arg!.length //相当与 arg && arg.length
}


//枚举-----------------

enum Color{
    red,
    green,
    yellow

}
console.log(Color.red)///0
console.log(Color.green)///1
console.log(Color.yellow)///2 打印的是下标

//反向映射
console.log(Color[0]) ///red

//给枚举复制
enum Color1{
    red,
    green="abc", 
    yellow=3  //如果前一个枚举值是字符串后一个枚举属性必须赋值
}

//泛型


function func4<T>(arg: T):void{

    
}
func4<number>(3)
func4<string>('abc')

转编译 需要新建 tsconfig.json 配置文件

ts转 js 需要 ts当前目录下终端执行 tsc xxxx.ts
编译 所有的 ts —> tsc
监视 tsc xxx.ts -w
监视全部 tsc -w
{
    // include  用来指定那些ts文件需要被编译
    // 路径 **表示任意目录   *表示任意文件
    
    "include":[
        // "./src/**/*"
        
    ],

    //exclude   用来表示不需要被编译的目录
    // 默认值【"node_modules","bower_component","jspm_packages""exclude":[
    // "./src/**/*"
    ],

    //outDie  用来指定编译后的js文件放在哪
    "outDie":"./dist" ,  //例如放在更目录的dist文件下 没有会新建

    //outFile 用来将所有全局作用域的ts代码合并成一个 js
    "outFile":"./dist/app.js" ,

    //compilerOptions 编译器的选项
    "compilerOptions":{
        // 例如   target用来指定被编译到ES版本
        "target":"ES5"//值必须是 【es3 es5 es6 es2015  es2016  es2017  es2018  es2019 es2020 esnext】
        
    },
    //modele 指定要使用的模块化的规范【none commnjs amd  system umd  es6 es2015 es2020 esnext】
    "module":"", //想合并代码  值必须是 amd  或者  system

    //lib 用来指定项目中用到的库  使用的时候会有提示
    //【很多...."lib": [
        "esnext",

      ],


      //  所有严格检查总开关   开启式 下面的模式都可以不写
     "strict": true,


      //allowJs 是否对js文件 进行编译 默认false
      "allowJs":false,
      //checkjs  是否检查js代码

      "checkJs":false,  //默认false


      // "removeComments" 是否移除注释
      "removeComments":true,


      //noEmit  不生成编译后的文件
      "noEmit":false,

      //noEmintOnError  ts代码有错误不进行编译
      "noEmintOnError":true,

      //用来设置编译后的文件是否使用严格模式
      "alwaysStrict" :false,


      //不允许不明确类型的this
      "noImplicitThis": true,

     
}

项目中的ts解析

<template>
  <div class="hello">
    <h2>Essential Links</h2>
   <p>{{firstName}}</p>
   <p>{{lastName}}</p>
   <p>{{fullName}}</p>
   <button @click="change"></button>
  </div>
</template>

<script lang="ts">
import {Component ,Vue} from 'vue-property-decorator'//装饰器插件
/** 有哪些----如下
 * @Componenr
 * @Watch
 * @Prop
 * @Model 
 * @Emit
 * 
 */
// export default{
//   name:'home'
// }
// @Component({
//   name:"home",
//   components:{
   

//   }
// })
// @Component

export default class home extends Vue{
  firstName :string="zhang";
  lastName :string="san";

  get fullName(){
    return  this.firstName+""+this.lastName
  }

  set fullName(val){

   const arr=val.split('')
   this.firstName=arr[0]
   this.lastName=arr[1]

  }
  change(){
    this.fullName="li si"

  }
  
  @Watch("firstName")
  onFirstNameChang (newVal,oldVal){
    console.log(newVal,oldVal)


  }

}

</script>

<style scoped>

</style>

webpack 打包模ts代码

首先初始化 npm init -y 对项目进行初始化 生成package.json

安装依赖 npm i -D webpack webpack-cli typescript ts-loader

还需要在package.json配置

“scripts”:{
“build:”"
}

编写webpack配置文件 新建webpack.config.js
const  path =require('path')


module.exports={

    // 指定入口文件
    entry:"./src/.....ts",
    output:{
        //指定打包文件的目录

        path:path.resolve(__dirname,'dist'),

        //打包后的文件名
        filename:'bundle.js'

    },
    module:{
        rules:[{
            //test指定的是规则生效的文件
            test:/\.ts$/,
            //要使用的loader
            use:'ts-loader',
            //要排除的文件
            exclude:/node-modules/
        }]
    }
}
打包插件 网页制动引入打包后的文件 插件配置webpack.config.js中

npm i -D html-webpack-plugin

const  path =require('path')
const HTMlWebPlugin= require('html-webpack-plugin')



module.exports={

    // 指定入口文件
    entry:"./src/.....ts",
    output:{
        //指定打包文件的目录

        path:path.resolve(__dirname,'dist'),

        //打包后的文件名
        filename:'bundle.js'

    },
    module:{
        rules:[{
            //test指定的是规则生效的文件
            test:/\.ts$/,
            //要使用的loader
            use:'ts-loader',
            //要排除的文件
            exclude:/node-modules/
        }]
    }
//配置webpack插件

plugin:{
new HTMlWebPlugin(options:{
	template:"./src/index.html" //指定打包的根html 打包后阿讲js 引入
}) ,
}
}
浏览器制动预览插件

npm i -D webpack-dev-server

还需要在package.json配置
“scripts”:{
"build:“webpack”,
“start”:“webpack serve --open chrome.exe”
}

打包覆盖dist

插件配置webpack.config.js中配置

npm i -D clean-webpack-plugin

//引入一个包
const  path =require('path')
//引入html插件
const HTMlWebPlugin= require('html-webpack-plugin')
//引入clean插件
const {CleanWebpackPlugin} = require('clean-webpack-plugin')



module.exports={

    // 指定入口文件
    entry:"./src/.....ts",
    output:{
        //指定打包文件的目录

        path:path.resolve(__dirname,'dist'),

        //打包后的文件名
        filename:'bundle.js'

    },
    module:{
        rules:[{
            //test指定的是规则生效的文件
            test:/\.ts$/,
            //要使用的loader
            use:'ts-loader',
            //要排除的文件
            exclude:/node-modules/
        }]
    },
//配置webpack插件

    plugin:{
    		new CleanWebpackPlugin(),//清除之前的dist文件
            new HTMlWebPlugin(options:{
          	template:"./src/index.html" //指定打包的根html 打包后阿讲js 引入
}) ,
}
}
ts内加载有ts文件 编译时会报错 在webpack.config.js里可以配置

//引入一个包
const  path =require('path')
//引入html插件
const HTMlWebPlugin= require('html-webpack-plugin')
//引入clean插件
const {CleanWebpackPlugin} = require('clean-webpack-plugin')



module.exports={

    // 指定入口文件
    entry:"./src/.....ts",
    output:{
        //指定打包文件的目录

        path:path.resolve(__dirname,'dist'),

        //打包后的文件名
        filename:'bundle.js'

    },
    module:{
        rules:[{
            //test指定的是规则生效的文件
            test:/\.ts$/,
            //要使用的loader
            use:'ts-loader',
            //要排除的文件
            exclude:/node-modules/
        }]
    },
//配置webpack插件

    plugin:{
    		new CleanWebpackPlugin(),//清除之前的dist文件
            new HTMlWebPlugin(options:{
          	template:"./src/index.html" //指定打包的根html 打包后阿讲js 引入
}) ,


//用来配置应用模块
   resolve:{
   extensions:[".ts",".js"]
}
}
}

打包浏览器兼容配置 这里忽略 点击跳转相关配置视频教程

不指定泛型 function fn(a:T):T{}
ts 中指定泛型
fn(a:“hello”)

vuex+ts 需要安装

npm i -S vuex-module-decorators

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端成长营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值