好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

webpack集成ts(typescript)

Typescript是一种基于静态类型检查的强类型语言

弱类型:javaScript是动态运行的弱类型语言,例如:
    var a=1;
   a='hello'
 
 强类型   列如:
     let str: string = 'hello ts';
    str=1
下面会给你显示:不能将类型“999”分配给类型“string”。

今年要发布vue3.0源码是用TS写的

typescript和javaScript是什么关系?

 typescript是javaScript的一个超集,比JS多了类型静态检查功能,  typeScript是由微软公司于2014年开发的,  浏览器不支持支持TypeScript,必须通过编译器把TypeScript编译成JS,才可以跑在浏览器 
 安装TypeScript编译器 :  npm install -g typescript 

typeScript官方文档:https://www.typescriptlang.org

 

webpack与TS集成

安装typescript

 npm install typescript ts-loader -D
 

配置ts-loader

  {test:/\.ts$/,exclude: /node_modules/,use:['ts-loader']}
 

创建tsconfig.json文件

 tsc --init
 

配置模块化引入文件的缺省类型

 const config = {
    //指定模式:production-生产环境,development:开发环境
    mode: "development",
    //项目的入口文件
    entry: "./src/main.ts",
    output: {
        //设置项目的输出目录
        path: path.resolve(__dirname, "dist"),
        //输出的文件名
        filename: "bundle.js" //chunk
    },

    //webpack通过loader识别文件的匹配规则
    module: {
        rules: [
            {test:/\.ts$/,exclude: /node_modules/,use:['ts-loader']}
        ]

    },
    //配置模块化引入文件的缺省类型
    resolve: {
        extensions:['.js','.ts']
    },
    plugins: [] 

TypeScript语法

 

TS数据类型

  支持所有的JS数据类型,还包括TS中添加的数据类型

JS基本数据类型有哪些:number,string,boolean,undefined,null

JS引用类型:Array,Object,function

TS除了上面支持的类型外,还支持:元组,枚举,any,void,never

JavaScript:
const user = { name: "Hayes", id: 0, };

TypeScript:

interface User { name: string; id: number; }

可以 interface 像 : TypeName 在变量声明之后 那样使用语法 来声明JavaScript对象符合新形状 :

const user: User = { name: "Hayes", id: 0, };

 

 

如果您提供的对象与您提供的接口不匹配,TypeScript会警告您:

interface User { name: string; id: number; } const user: User = { username: "Hayes",

 

Type '{ username: string; id: number; }' is not assignable to type 'User'. Object literal may only specify known properties, and 'username' does not exist in type 'User'. Type '{ username: string; id: number; }' is not assignable to type 'User'. Object literal may only specify known properties, and 'username' does not exist in type 'User'.

 

id: 0, };

 

TypeScript了解代码如何随时间改变变量的含义,您可以使用这些检查来缩小类型的范围。

类型 谓语
typeof s === "string"
typeof n === "number"
布尔值 typeof b === "boolean"
未定义 typeof undefined === "undefined"
功能 typeof f === "function"
数组 Array.isArray(a)

 

 

官方ts文档: https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

 

查看更多关于webpack集成ts(typescript)的详细内容...

  阅读:54次