当前位置:网站首页>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.z
To 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 aliasvar
Value of the variable values will not affect the original.
5.使用其它的JavaScript库
5.1 External space obviously
Popular librariesD3在全局对象d3
Define 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.ts
Statement 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
.
边栏推荐
- npm ERR! 400 Bad Request - PUT xxx - Cannot publish over previously published version “1.0.0“.
- 软件测试H模型
- wireshark的安装教程(暖气片安装方法图解)
- Pytorch's LSTM parameters explained
- 鸿星尔克再捐一个亿
- 重磅大咖来袭!阿里云生命科学与智能计算峰会精彩内容剧透
- js防抖函数和函数节流的应用场景
- Supervised learning of Li Hang's "Statistical Learning Methods" Notes
- R language ggplot2 visualization: use the ggbarplot function of the ggpubr package to visualize the stacked bar plot, the lab.pos parameter specifies the position of the numerical label of the bar cha
- LayaBox---TypeScript---高级类型
猜你喜欢
随机推荐
The R language uses the ggtexttable function of the ggpubr package to visualize the table data (draw the table directly or add the table data to the image), set the theme parameter to customize the fi
List-based queuing and calling system
行为型模式-策略模式
利用二维数据学习纹理三维网格生成(CVPR 2020)
One Summer of Open Source | How to Quickly Integrate Log Modules in GO Language Framework
LayaBox---TypeScript---Symbols
周杰伦新歌发布,爬取《Mojito》MV弹幕,看看粉丝们都说的些啥!
The love-hate relationship between C language volatile keyword, inline assembly volatile and compiler
LayaBox---TypeScript---高级类型
使用较广泛的安全测试工具有哪些?
QT专题:事件机制event基础篇
R语言时间序列数据算术运算:使用log函数将时间序列数据的数值对数化、使用diff函数计算对数化后的时间序列数据的逐次差分(计算价格的对数差分)
R语言时间序列数据的平滑:使用KernSmooth包的dpill函数和locpoly函数对时间序列数据进行平滑以消除噪声
The perceptron perceptron of Li Hang's "Statistical Learning Methods" notes
The realization of the list
Use the scrapy to climb to save data to mysql to prevent repetition
用正向迭代器封装实现反向迭代器
Pytorch's LSTM parameters explained
后管实现面包屑功能
Weak yen turns game consoles into "financial products" in Japan: scalpers make big profits