Typescript 的语法进阶基础之的命名空间、模块化和类型描述文件
#
一、Typescript 的命名空间和模块化
- “内部模块”现在称做“命名空间”。 “外部模块”现在则简称为“模块”。“内部模块”现在叫做“命名空间”,任何使用
module
关键字来声明一个内部模块的地方都应该使用namespace
关键字来替换。随着更多验证器的加入,我们需要一种手段来组织代码,以便于在记录它们类型的同时还不用担心与其它对象产生命名冲突。 因此,我们把验证器包裹到一个命名空间内,而不是把它们放在全局命名空间下。如果想让这些接口和类在命名空间之外也是可访问的,所以需要使用export
。反之,没有使用export
在命名空间外是不能访问的。 命名空间
Home
, 将四个变量放到一个命名空间中。命名空间生成的,也可以理解为 命名变量。命名空间的好处,类似模块化开发的好处,能尽量少的声明全局变量,把一组相关的内容封装到一起去,对外提供统一的暴露接口。在下面中,Page
是直接暴露,其余三个是间接是间接暴露,index.html
是页面,page.ts
是ts
文件,page.js
是编译ts
文件后生成的js
文件,代码如下所示:index.html
<!DOCTYPE html>
Document
page.ts
namespace Home {
class Header {constructor() {
const elem = document.createElement("div");
elem.innerText = "this is header";
document.body.appendChild(elem);
}
}
class Content {
constructor() {
const elem = document.createElement("div");
elem.innerText = "this is content";
document.body.appendChild(elem);
}
}
class Footer {
constructor() {
const elem = document.createElement("div");
elem.innerText = "this is footer";
document.body.appendChild(elem);
}
}
export class Page {
constructor() {
new Header();
new Content();
new Footer();
}
}
}page.js
“use strict”;
var Home;
(function (Home) {var Header = /** @class */ (function () {
function Header() {
var elem = document.createElement("div");
elem.innerText = "this is header";
document.body.appendChild(elem);
}
return Header;
}());
var Content = /** @class */ (function () {
function Content() {
var elem = document.createElement("div");
elem.innerText = "this is content";
document.body.appendChild(elem);
}
return Content;
}());
var Footer = /** @class */ (function () {
function Footer() {
var elem = document.createElement("div");
elem.innerText = "this is footer";
document.body.appendChild(elem);
}
return Footer;
}());
var Page = /** @class */ (function () {
function Page() {
new Header();
new Content();
new Footer();
}
return Page;
}());
Home.Page = Page;
})(Home || (Home = { }));
分离到多文件,当应用变得越来越大时,我们需要将代码分离到不同的文件中以便于维护。尽管是不同的文件,它们仍是同一个命名空间,并且在使用的时候就如同它们在一个文件中定义的一样。 因为不同文件之间存在依赖关系,所以我们加入了引用标签来告诉编译器文件之间的关联。多文件确保所有编译后的代码都被加载,有两种方式。第一种方式,把所有的输入文件编译为一个输出文件,需要使用
--outFile
标记,编译器会根据源码里的引用标签自动地对输出进行排序,也可以单独地指定每个文件。第二种方式,我们可以编译每一个文件(默认方式),那么每个源文件都会对应生成一个JavaScript
文件。 然后,在页面上通过<script>
标签把所有生成的JavaScript
文件按正确的顺序引进来。如下,在子命名空间
Components
中,还可以再使用子命名空间,可以使用接口,也可以使用类。Home
的这个命名空间,依赖于components.ts
这个文件,需要做引用标签。同时,修改tsconfig.json
文件,修改module、outFile、outDir 和 rootDir
,代码如下所示:index.html
<!DOCTYPE html>
Document
components.ts
namespace Components {
export namespace SubComponents {export class Test { }
}
export interface User {
name: string;
}
export class Header {
constructor() {
const elem = document.createElement("div");
elem.innerText = "this is header";
document.body.appendChild(elem);
}
}
export class Content {
constructor() {
const elem = document.createElement("div");
elem.innerText = "this is content";
document.body.appendChild(elem);
}
}
export class Footer {
constructor() {
const elem = document.createElement("div");
elem.innerText = "this is footer";
document.body.appendChild(elem);
}
}
}page.ts
///
namespace Home {
export const people: Components.User = {name: "Tom",
};
export class Page {
constructor() {
new Components.Header();
new Components.Content();
new Components.Footer();
}
}
}tsconfig.json
{
“compilerOptions”: {/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "amd",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
"outFile": "./dist/page.js",
/* Concatenate and emit output to single file. */
"outDir": "./dist",
/* Redirect output structure to the directory. */
"rootDir": "./src",
/* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true,
/* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true,
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true,
/* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
别名,简化命名空间操作的方法,为指定的符号创建一个别名。你可以用这种方法为任意标识符创建别名,也包括导入的模块中的对象。我们使用
import
语句对模块进行拆分与组合,打包后生成AMD
规范,代码如下所示:index.html
<!DOCTYPE html>
Document
components.ts
export class Header {
constructor() {const elem = document.createElement("div");
elem.innerText = "this is header";
document.body.appendChild(elem);
}
}export class Content {
constructor() {const elem = document.createElement("div");
elem.innerText = "this is content";
document.body.appendChild(elem);
}
}export class Footer {
constructor() {const elem = document.createElement("div");
elem.innerText = "this is footer";
document.body.appendChild(elem);
}
}page.ts
import { Header, Content, Footer } from “./components”;
class Page {
constructor() {new Header();
new Content();
new Footer();
}
}
使用
Parcel
工具对于TS
文件进行打包,Parcel
可以编译TS
文件,通过npm install parcel-bundler --save-dev
命令下载Parcel
到本地项目中,通过npm run dev
命令运行项目,代码如下所示:index.html
<!DOCTYPE html>
Document
page.ts
const people: string = “Tom”;
console.log(people);package.json
{
“name”: “TypeScript”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {"test": "parcel ./src/index.html"
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“devDependencies”: {"parcel": "^2.0.0-alpha.3.2"
}
}tsconfig.json
{
“compilerOptions”: {/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist",
/* Redirect output structure to the directory. */
"rootDir": "./src",
/* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true,
/* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true,
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true,
/* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
二、Typescript 的描述文件
类型定义文件,帮助
TS
文件理解引入的js
文件或js
库文件的内容,以.d.ts
的形式结尾的文件。使用declare
可以定义全局的变量或者是函数。一个函数可以有多种形式,也可以称为为 函数的重载,代码如下所示:index.html
<!DOCTYPE html>
Document
page.ts
$(function () {
$(“body”).html(“123“);
});jquery.d.ts
interface JqueryInstance {
html: (html: string) => { };
}declare function $(readyFunc: () => void): void;
declare function $(selector: string): JqueryInstance;
使用
interface
的语法,实现函数重载。如何对对象进行类型定义,以及如何对类进行类型定义,以及命名空间的嵌套,代码如下所示:index.html
<!DOCTYPE html>
Document
page.ts
$(function () {
$(“body”).html(“123“);
new $.fn.init();
});jquery.d.ts
interface JqueryInstance {
html: (html: string) => { };
}declare function $(readyFunc: () => void): void;
declare function $(selector: string): JqueryInstance;declare namespace $ {
namespace fn {class init { }
}
}// 使用 interface 的语法,实现函数重载
// interface JQuery {
// (readyFunc: () => void): void;
// (selector: string): JqueryInstance;
// }// declare var $: JQuery;
对于类型描述文件,也可以使用模块化的代码,使用
ES6
模块化以及混合类型,如下所示:index.html
<!DOCTYPE html>
Document
page.ts
import $ from ‘jquery’;
$(function() {
$(‘body’).html(‘123‘);
new $.fn.init();
});jquery.d.ts
declare module ‘jquery’ {
interface JqueryInstance {html: (html: string) => JqueryInstance;
}
function $(readyFunc: () => void): void;
function $(selector: string): JqueryInstance;
namespace $ {namespace fn {
class init { }
}
}
export = $;
}
还没有评论,来说两句吧...