webpack集成ts(typescript)


typscript是什么?

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集成

  1. 安裝typescript

    npm install typescript ts-loader -D
    
  2. 配置ts-loader

     {test:/\.ts$/,exclude: /node_modules/,use:['ts-loader']}
    
  3. 創建tsconfig.json文件

    tsc --init
    
  4. 配置模塊化引入文件的缺省類型

    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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM