【第5篇】TypeScript塊module的案例代碼詳解

1 、分多個ts文件實現(xiàn)module塊

  • Validation.ts代碼
module Validation{ 
    export interface StringValidator { 
         isAcceptable(s: string): boolean;//是否接受.
    }
}
  • ZipCodeValidator.ts代碼
/// <reference path="Validation.ts" />
module Validation {
   //匹配0-9的數(shù)字.
    var numberRegexp = /^[0-9]+$/;
    export class ZipCodeValidator implements StringValidator {
        isAcceptable(s: string) {
            //如果長度=5并且是數(shù)字就返回一個true
            return s.length === 5 && numberRegexp.test(s);
        }
    }
}
  • LettersOnlyValidator.ts代碼
/// <reference path="Validation.ts" />
module Validation {
    //匹配A-Z,a-z的英文
    var lettersRegexp = /^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }}

  • test-1.ts代碼
/// <reference path="../plugins/typescript/typings/jquery.d.ts" />
/// <reference path="test1/Validation.ts" />
/// <reference path="test1/LettersOnlyValidator.ts" />
/// <reference path="test1/ZipCodeValidator.ts" />

/***
 * Splitting Across Files分割跨文件
 */
// 聲明一個數(shù)組.
var strings = ['Hello', '98052', '101'];
// 使用這個驗證.
var validators: { [s: string]: Validation.StringValidator; } = {};
validators['Zip Code'] = new Validation.ZipCodeValidator();//這個是驗證郵政編碼
validators['Letters only'] = new Validation.LettersOnlyValidator();//這個是驗證英文

function showMsg():void{ 
    //顯示每個字符串是否通過每個驗證
    strings.forEach(s => {
        for (var name in validators) {
            console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name);

            $("#msg1").html('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name);
        }//--for--end

    });//--forEach--end
}

$(document).ready(function(){ 
    showMsg();
   
});
  • Html 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="../../plugins/jquery-2.1.4.min.js"></script>
<script src="../test1/Validation.js" type="text/javascript"></script>
<script src="../test1/LettersOnlyValidator.js" type="text/javascript"></script>
<script src="../test1/ZipCodeValidator.js" type="text/javascript"></script>
<script src="../test-1.js" type="text/javascript"></script>
</head>
<body>
<div id="msg1"></div>
<br/>
<div id="msg2"></div>
</body>
</html>
 

2、 不分文件實現(xiàn)module塊

  • ValidationUtils.ts
/**
 *聲明一個ValidationUtils工具塊module
 *推薦使用.
 */
module ValidationUtils{ 
    //-聲明StringValidator字符串驗證器.
     export interface StringValidator { 
         isAcceptable(str: string): boolean;//是否接受.
    }

    // 匹配email正則表達式
    var emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    export class EmailValidator implements StringValidator {
        isAcceptable(s: string) {
            return emailReg.test(s);
        }
    }
    //匹配移動電話號碼
    var telReg=/^(13[0-9]|15[0-9]|18[0-9])\d{8}$/;
    export class TelValidator implements StringValidator{ 
         isAcceptable(s:string){ 
            return  telReg.test(s);
         }
    }
}
  • 測試文件test-2.ts
/// <reference path="../plugins/typescript/typings/jquery.d.ts" />
/// <reference path="test2/ValidationUtils.ts" />
var strs : Array<any> =["13697811800","jilongliang@sina.com"];
var validators1: { [s: string]: ValidationUtils.StringValidator; } = {};
validators1["Tel"]=new ValidationUtils.TelValidator;//驗證碼QQ
validators1["Email"] = new ValidationUtils.EmailValidator;//驗證Email

//-------顯示信息1----------------------------
function showMsg1():void{ 
    strs.forEach(s=>
      {
        for(var name in validators1 ){  
            console.log('"' + s + '" ' + (validators1[name].isAcceptable(s) ? ' 匹配 ' : ' 不匹配 ') + name);
        }
      }
   );
}
//-------------------顯示信息2---------------------
function showMsg2():void{ 

    //--方法一---
    var telObj:ValidationUtils.TelValidator;
    telObj=new ValidationUtils.TelValidator;
     //--方法二---
     //var telObj=new ValidationUtils.TelValidator;
    var tel : string="13697811809";
    var flag : boolean=telObj.isAcceptable(tel);//調(diào)用TelValidator類的isAcceptable方法
    console.log(flag? tel+" 匹配 " : tel+"\t 不匹配 ");
    $("#msg2").html(flag? "<span style='color:red;'>"+tel+" 匹配</span> " : "<span>"+tel+"\t 不匹配</span>");
}
$(function(){ 
    showMsg1();
    showMsg2();
});

  • html 代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="../../plugins/jquery-2.1.4.min.js"></script>
<script src="../test2/ValidationUtils.js" type="text/javascript"></script>
<script src="../test-2.js" type="text/javascript"></script>
</head>
<body>
<div id="msg1"></div>
<br/>
<div id="msg2"></div>
</body>
</html>
 

3 、import,require關(guān)鍵字

  • ValidationUtils3.ts文件
/* 這個ts沒module關(guān)鍵字*/
export interface StringValidator {
    isAcceptable(s: string): boolean;
}
  • EmailValidator.ts
 /**import、require、export關(guān)鍵的使用..***********/
    //--導(dǎo)入--ValidationUtils3.ts文件---
    import validation = require('./ValidationUtils3');
    // 匹配email正則表達式
    var emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    export class EmailValidator implements validation.StringValidator {
        isAcceptable(s: string) {
            return emailReg.test(s);
        }
    }
  • TelValidator.ts
/**import、require、export關(guān)鍵的使用..***********/
//--導(dǎo)入--ValidationUtils3.ts文件---
import validation = require('./ValidationUtils3');
    //匹配移動電話號碼
    var telReg=/^(13[0-9]|15[0-9]|18[0-9])\d{8}$/;
    export class TelValidator implements validation.StringValidator{ 
         isAcceptable(s:string){ 
            return  telReg.test(s);
         }
    }
  • Test-3.ts
/// <reference path="../plugins/typescript/typings/jquery.d.ts" />
/***
 * import與require關(guān)鍵字使用..require(是命令,要求的意思.)
 */
//引入ValidationUtils3.ts文件,前面這個是用了module塊關(guān)鍵字定義ts文件,需要用reference與path引入.
import validation = require('test3/ValidationUtils3');
import telValidator = require('test3/TelValidator');
import emailValidator = require('test3/EmailValidator');


//-------------------顯示信息1---------------------
function showMsgs1() : void { 
    //--方法一---
    var  telObj=new emailValidator.EmailValidator();//
    var tel : string="13697811809";
    //調(diào)用TelValidator類的isAcceptable方法
    var flag : boolean=telObj.isAcceptable(tel);
    console.log(flag? tel+" 匹配 " : tel+"\t 不匹配 ");
    $("#msg1").html(flag? "<span style='color:red;'>"+tel+" 匹配</span> " : "<span>"+tel+"\t 不匹配</span>");
}


$(function() { 
    //showMsgs1();
var strings = ['13697811809', 'jilongliang@sina.com'];
var validators: { [s: string]: validation.StringValidator; } = {};
validators['email'] =new emailValidator.EmailValidator();
validators['tel'] = new telValidator.TelValidator();
strings.forEach(s => {
    for (var name in validators) {
        console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? ' matches ' : ' does not match ') + name);
    }
});
});

4、import,export,require關(guān)鍵字

  • ValidationUtils4.ts
/**
 * 不使用Module,如果我們在typescript使用了module函數(shù),則生成的代碼在瀏覽器端執(zhí)行時,需要有一些script loader的支持。
 * 對于瀏覽器端代碼,我們一般生成amd風格的代碼,所以需要找一個支持amd的庫放在前端。這樣的庫有很多
 */
export interface StringValidator {
    isAcceptable(s: string): boolean;
}
  • export = 對象 的使用
  • EmailValidator4.ts
/**export = 對象 的使用*/
    import validation = require('./ValidationUtils4');
    // 匹配email正則表達式
    var emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
     class EmailValidator4 implements validation.StringValidator {
        isAcceptable(s: string) {
            return emailReg.test(s);
        }
    }
    export = EmailValidator4; //export = 對象 的使用
  • TelValidator4.ts
/**export = 對象 的使用*/
    import validation = require('./ValidationUtils4');
    //匹配移動電話號碼
    var telReg=/^(13[0-9]|15[0-9]|18[0-9])\d{8}$/;
     class TelValidator4 implements validation.StringValidator{ 
         isAcceptable(s:string){ 
            return  telReg.test(s);
         }
    }
    export = TelValidator4;//
  • Test-4.ts文件
/// <reference path="../plugins/typescript/typings/jquery.d.ts" />
//引入ValidationUtils3.ts文件,前面這個是用了module塊關(guān)鍵字定義ts文件,需要用reference與path引入.
import validation = require('test4/ValidationUtils4');
import telValidator = require('test4/TelValidator4');
import emailValidator = require('test4/EmailValidator4');
//-------------------顯示信息1---------------------
function showMsgs1() : void { 
    //--方法一---
    var  telObj=new telValidator();//
    var tel : string="13697811809";
;//調(diào)用TelValidator類的isAcceptable方法
    var flag : boolean=telObj.isAcceptable(tel)
    console.log(flag? tel+" 匹配 " : tel+"\t 不匹配 ");
    $("#msg1").html(flag? "<span style='color:red;'>"+tel+" 匹配</span> " : "<span>"+tel+"\t 不匹配</span>");
}
$(function (){ 
    showMsgs1();
});

注意:3和4不使用Module,如果我們在typescript使用了module函數(shù),則生成的代碼在瀏覽器端執(zhí)行時,需要有一些script loader的支持。對于瀏覽器端代碼,我們一般生成amd風格的代碼,所以需要找一個支持amd的庫放在前端,我這里首選的是AMD這樣的庫有很多,比如 RequireJS 、 Nodules、 JSLocalnet 、 curl.js

  • 不然的話運行這個html會報ReferenceError: define is not defined

5、module別名的使用

//------------別名的使用..
//--聲明一個--Shapes塊別名--
module Shapes { 
     //===========================多邊形===========================
     export module Polygons { 
        //===========================三角形
        export class Triangle {  
            side : number = 3;//聲明邊一個變量,并且給一個默認值..
            theName : string;//聲明一個名字
            //聲明構(gòu)造方法--傳一個名字的參數(shù)..
            constructor(strName : string) { 
                this.theName = strName;
            }
            //計算三角形,獲取面積,這里為了返回一個構(gòu)造方法的傳進來的字符串,故返回類型給了一個any類型..
            getTriangleArea(side : number) : any{ 
               return this.theName+ this.side*side;
            }
        }

        //===========================正方形
        export class Square { 
            side : number = 8;//聲明邊一個變量,并且給一個默認值..
            theName : string;//聲明一個名字
            //聲明構(gòu)造方法--傳一個名字的參數(shù)..
            constructor(strName : string) { 
                this.theName = strName;
            }
            //---計算正方形,獲取面積
            getSquareArea(side : number) : any{ 
               return this.theName+ this.side*side;
            }
        }
    }
}
  • ts編譯成js文件
//------------別名的使用..
//--聲明一個--Shapes塊別名--
var Shapes;
(function (Shapes) {
    //==========================多邊形===========================
    var Polygons;
    (function (Polygons) {
        //===========================三角形
        var Triangle = (function () {
            //聲明構(gòu)造方法--傳一個名字的參數(shù)..
            function Triangle(strName) {
                this.side = 3; //聲明邊一個變量,并且給一個默認值..
                this.theName = strName;
            }

            //計算三角形,獲取面積,這里為了返回一個構(gòu)造方法的傳進來的字符串,
//故返回類型給了一個any類型..
            Triangle.prototype.getTriangleArea = function (side) {
                return this.theName + this.side * side;
            };
            return Triangle;
        })();
        Polygons.Triangle = Triangle;
        //===========================正方形
        var Square = (function () {
            //聲明構(gòu)造方法--傳一個名字的參數(shù)..
            function Square(strName) {
                this.side = 8; //聲明邊一個變量,并且給一個默認值..
                this.theName = strName;
            }
            //---計算正方形,獲取面積
            Square.prototype.getSquareArea = function (side) {
                return this.theName + this.side * side;
            };
            return Square;
        })();
        Polygons.Square = Square;
    })(Polygons = Shapes.Polygons || (Shapes.Polygons = {}));
})(Shapes || (Shapes = {}));

6、module內(nèi)部模塊

  • D3.d.ts文件,.d.ts文件不會編譯成js文件
//環(huán)境內(nèi)部模塊
declare module D3{ 
   //聲明一個Selectors選擇器接口
   export interface Selectors {
        select: {
            (selector: string): Selection;
            (element: EventTarget): Selection;
        };
    }
     //聲明一個Event事件
    export interface Event {
        x: number;
        y: number;
    }
     //聲明一個Base接口繼承Selectors接口
    export interface Base extends Selectors {
        event: Event;
    }
}

7、module外部模塊

  • node.d.ts
//環(huán)境外部模塊
//在node.js中,大多數(shù)的任務(wù)是由加載一個或多個模塊來實現(xiàn)的。我們可以定義自己的.d.ts文件頂層出口報關(guān)單每個模塊,但它更方便他們寫為一個較大的.d.ts文件。要做到這一點,我們使用了模塊的引用名,這將提供給一個后來進口
declare module "url" {
    export interface Url {
        protocol?: string;
        hostname?: string;
        pathname?: string;
    }
    export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;
}
declare module "path" {
    export function normalize(p: string): string;
    export function join(...paths: any[]): string;
    export var sep: string;
}


  • 引入node.d.ts文件
/引入node.d.ts文件
///<reference path="test6/node.d.ts"/>
import url = require("url");
var myUrl = url.parse("http://www.typescriptlang.org");
$(function() { 
    alert(myUrl);
    //$("#msg1").html(myUrl);
});

工程源代碼

TypeScript塊module的案例代碼詳解

博客所有文章是本人2014年撰寫,而GItHub的源代碼是有些是2014年與2015年進行整理,由于在2013年項目接觸TypeScript,同時在當年接觸KendoUI開發(fā)的時候TypeScript的影子,故一年后決定把官方文檔所有API文檔認真琢磨了一遍,并且撰寫成一本最全的中文TypeScript入門指南詳解案例教程與代碼,當初的下載量還是比較高的。由于最近接觸Kotlin,自從學習TypeScript,它的語法對我后面學習Kotlin有了極大的幫助,個人感覺,它的語法跟ActionScript,Swift寫法很像。故雖然好幾年沒怎么開發(fā)前端,由于它的重要性特意重新花點進行整理這門前端語言。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 慕課網(wǎng)@JoJozhai 老師 TypeScript入門課程分享 TypeScript入門 ES5,ES6,JS,...
    shangpudxd閱讀 10,642評論 0 22
  • 使用Visual Studio Code搭建TypeScript開發(fā)環(huán)境 1、TypeScript是干什么的 ? ...
    KingOfLion閱讀 1,772評論 0 8
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標準。 注意:講述HT...
    kismetajun閱讀 28,826評論 1 45
  • 這一章主要總結(jié)TypeScript的用法和項目常用配置 編譯上下文 用來給文件分組,告訴 TypeScript 哪...
    Terryzh閱讀 2,136評論 0 0
  • 準假期里,某老師養(yǎng)精為業(yè)。無聊中,憶起小樹林。忽見樹林外,大約數(shù)百米,密圍鐵皮,見的樹木,不見路口。老師甚為急。復(fù)...
    云影ccl閱讀 368評論 2 1

友情鏈接更多精彩內(nèi)容