当前位置:网站首页>LayaBox---TypeScript---Namespaces and modules
LayaBox---TypeScript---Namespaces and modules
2022-08-02 10:13:00 【Gragra】
目录
3.Separation to multiple files
3.1 Multiple file naming space
7. The trap of namespaces and modules
1.介绍
Let's write a program and will be used in the whole article this example.
All of the validator in a file
interface StringValidator {
isAcceptable(s: string): boolean;
}
let lettersRegexp = /^[A-Za-z]+$/;
let numberRegexp = /^[0-9]+$/;
class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
// Some samples to try
let strings = ["Hello", "98052", "101"];
// Validators to use
let validators: { [s: string]: StringValidator; } = {};
validators["ZIP code"] = new ZipCodeValidator();
validators["Letters only"] = new LettersOnlyValidator();
// Show whether each string passed each validator
for (let s of strings) {
for (let name in validators) {
let isMatch = validators[name].isAcceptable(s);
console.log(`'${ s }' ${ isMatch ? "matches" : "does not match" } '${ name }'.`);
}
}2.命名空间
随着更多验证器的加入,We need a means to organize the code,以便于在记录它们类型的同时还不用担心与其它对象产生命名冲突.
2.1Use namespace validator
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
const lettersRegexp = /^[A-Za-z]+$/;
const numberRegexp = /^[0-9]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
// Some samples to try
let strings = ["Hello", "98052", "101"];
// Validators to use
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();
// Show whether each string passed each validator
for (let s of strings) {
for (let name in validators) {
console.log(`"${ s }" - ${ validators[name].isAcceptable(s) ? "matches" : "does not match" } ${ name }`);
}
}3.Separation to multiple files
当应用变得越来越大时,我们需要将代码分离到不同的文件中以便于维护.
3.1 Multiple file naming space
现在,我们把Validation命名空间分割成多个文件. 尽管是不同的文件,它们仍是同一个命名空间,并且在使用的时候就如同它们在一个文件中定义的一样. 因为不同文件之间存在依赖关系,所以我们加入了引用标签来告诉编译器文件之间的关联.
---------Validation.ts--------------------------------------------
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
------------LettersOnlyValidator.ts-------------------------------
/// <reference path="Validation.ts" />
namespace Validation {
const lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
}
-------------ZipCodeValidator.ts-----------------------------------
/// <reference path="Validation.ts" />
namespace Validation {
const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
-------------Test.ts------------------------------------------------
/// <reference path="Validation.ts" />
/// <reference path="LettersOnlyValidator.ts" />
/// <reference path="ZipCodeValidator.ts" />
// Some samples to try
let strings = ["Hello", "98052", "101"];
// Validators to use
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();
// Show whether each string passed each validator
for (let s of strings) {
for (let name in validators) {
console.log(`"${ s }" - ${ validators[name].isAcceptable(s) ? "matches" : "does not match" } ${ name }`);
}
}当涉及到多文件时,我们必须确保所有编译后的代码都被加载了.
我们有两种方式.
第一种方式,把所有的输入文件编译为一个输出文件,需要使用--outFile标记:
tsc --outFile sample.js Test.ts
编译器会根据源码里的引用标签自动地对输出进行排序.You also can specify each file separately.
tsc --outFile sample.js Validation.ts LettersOnlyValidator.ts ZipCodeValidator.ts Test.ts第二种方式,We can compile each file(默认方式),So every source file corresponding to generate aJavaScript文件.
然后,在页面上通过 <script>标签把所有生成的JavaScript文件按正确的顺序引进来,
比如:
MyTestPage.html (excerpt)
<script src="Validation.js" type="text/javascript" />
<script src="LettersOnlyValidator.js" type="text/javascript" />
<script src="ZipCodeValidator.js" type="text/javascript" />
<script src="Test.js" type="text/javascript" />4.别名
The operation method is to use a simplified namespace
import q = x.y.zTo the common object of a short name. 不要与用来加载模块的import x = require('name')语法弄混了,这里的语法是为指定的符号创建一个别名. You can create an alias for an arbitrary identifier in this way,Also includes the import of the object in the module.
namespace Shapes {
export namespace Polygons {
export class Triangle { }
export class Square { }
}
}
import polygons = Shapes.Polygons;
// Same as "new Shapes.Polygons.Square()"
let sq = new polygons.Square();️注意:
1.我们并没有使用
require关键字,而是直接使用导入符号的限定名赋值.2.这与使用
var相似,但它还适用于类型和导入的具有命名空间含义的符号.3.重要的是,对于值来讲,
import会生成与原始符号不同的引用,So change the aliasvarValue of the variable values will not affect the original.
5.使用其它的JavaScript库
5.1 External space obviously
Popular librariesD3在全局对象d3Define its functions. Because the library through a <script>标签加载(Not by module loader),Statement of its files using internal module to define its type. 为了让TypeScriptThe compiler to identify its type,We use external namespace declaration.
比如:
D3.d.ts (部分摘录)
declare namespace D3 {
export interface Selectors {
select: {
(selector: string): Selection;
(element: EventTarget): Selection;
};
}
export interface Event {
x: number;
y: number;
}
export interface Base extends Selectors {
event: Event;
}
}
declare var d3: D3.Base;6.命名空间和模块
命名空间是位于全局命名空间下的一个普通的带有名字的JavaScript对象.
These can be used in multiple files at the same time,并通过
--outFile结合在一起. Namespace is to help you organize yourWebApplication of good way,You can put all rely onHTML页面的<script>标签里.
Modules like namespace,Can contain code and statement. Different modules can be 声明它的依赖.
Module will add dependence to module loader on(例如CommonJs / Require.js).Module also provides a better code reuse,The seal of the stronger and better tools to optimize the use of.
7. The trap of namespaces and modules
7.1 对模块使用
一个常见的错误是使用/// <reference>引用模块文件,应该使用import. To understand the difference between the,We should first find out how the compiler according to import路径(例如,import x from "...";或import x = require("...")里面的...,等等)To locate the module type information.
编译器首先尝试去查找相应路径下的.ts,.tsx再或者.d.ts. 如果这些文件都找不到,编译器会查找 外部模块声明. 回想一下,它们是在 .d.tsStatement in the file.
------------------------myModules.d.ts---------------------
// In a .d.ts file or .ts file that is not a module:
declare module "SomeModule" {
export function fn(): string;
}
//----------myOtherModule.ts---------------------------------
/// <reference path="myModules.d.ts" />
import * as m from "SomeModule";Here a reference tag to specify the position of foreign module. 这就是一些TypeScriptCase reference node.d.ts的方法.
7.2 不必要的命名空间
If you want to convert the namespace to module,It may be like the following file a:
---------------shapes.ts--------------------------------------------
export namespace Shapes {
export class Triangle { /* ... */ }
export class Square { /* ... */ }
}
Top of the moduleShapes包裹了Triangle和Square. It is confusing for the use of its people and hate:
--------------shapeConsumer.ts-------------------------------------
import * as shapes from "./shapes";
let t = new shapes.Shapes.Triangle(); // shapes.Shapes?不应该对模块使用命名空间,使用命名空间是为了提供逻辑分组和避免命名冲突. 模块文件本身已经是一个逻辑分组,并且它的名字是由导入这个模块的代码指定,所以没有必要为导出的对象增加额外的模块层.
The following is an example of an improvement:
------------shapes.ts--------------------------
export class Triangle { /* ... */ }
export class Square { /* ... */ }
---------shapeConsumer.ts----------------------
import * as shapes from "./shapes";
let t = new shapes.Triangle();7.3 Module choice
就像每个JSFile corresponding to a module,TypeScriptIn the module file with the generatedJSFile is one-to-one. This produces an effect,According to you specify the target system of module is different,You may not be able to connect multiple modules source file. For example, when the object module system for commonjs或umd时,无法使用outFile选项,但是在TypeScript 1.8以上的版本能够使用outFile当目标为amd或system.
边栏推荐
- How to choose a truly "easy-to-use, high-performance" remote control software
- 你好,我的新名字叫“铜锁/Tongsuo”
- MySql tens of millions of paging optimization, fast insertion method of tens of millions of data
- LayaBox---TypeScript---模块解析
- 如何选择一块真正“好用的、性能高”的远程控制软件
- Long battery life or safer?Seal and dark blue SL03 comparison shopping guide
- 阿里巴巴 CTO 程立:开源是基础软件的源头!
- LayaBox---TypeScript---装饰器
- js防抖函数和函数节流的应用场景
- 向量点积(Dot Product),向量叉积(Cross Product)
猜你喜欢
随机推荐
要长续航还是更安全?海豹与深蓝SL03对比导购
Smoothing of time series data in R language: smoothing time series data to remove noise using the dpill function and locpoly function of the KernSmooth package
HikariCP database connection pool, too fast!
全新荣威RX5,27寸大屏吸引人,安全、舒适一个不落
Pytorch's LSTM parameters explained
重磅大咖来袭!阿里云生命科学与智能计算峰会精彩内容剧透
This article takes you to understand the commonly used models and frameworks of recommender systems
R language ggplot2 visualization: based on the fill parameter and shape parameter in the aes function, custom draw a grouped line chart and add data points (scatter points), use the legend.position fu
Long battery life or safer?Seal and dark blue SL03 comparison shopping guide
超赞!发现一个APP逆向神器!
如何封装微信小程序的 wx.request() 请求
【云原生】快出数量级的性能是怎样炼成的?就提升了亿点点
Shell script realizes multi-select DNS simultaneous batch resolution of domain name IP addresses (new update)
未知内容监控
食品安全 | 鱼肝油不是鱼油,家有宝宝的注意了
21年毕业转行软件测试,从0收入到月薪过万,我真的很幸运...
第十五章 多线程
开源一夏 | GO语言框架中如何快速集成日志模块
Weak yen turns game consoles into "financial products" in Japan: scalpers make big profits
LayaBox---TypeScript---模块









