Typescript 的语法进阶基础之的命名空间、模块化和类型描述文件

深碍√TFBOYSˉ_ 2023-02-17 03:39 26阅读 0赞

#

一、Typescript 的命名空间和模块化

  1. “内部模块”现在称做“命名空间”。 “外部模块”现在则简称为“模块”。“内部模块”现在叫做“命名空间”,任何使用 module 关键字来声明一个内部模块的地方都应该使用 namespace 关键字来替换。随着更多验证器的加入,我们需要一种手段来组织代码,以便于在记录它们类型的同时还不用担心与其它对象产生命名冲突。 因此,我们把验证器包裹到一个命名空间内,而不是把它们放在全局命名空间下。如果想让这些接口和类在命名空间之外也是可访问的,所以需要使用 export。反之,没有使用 export 在命名空间外是不能访问的。
  2. 命名空间 Home, 将四个变量放到一个命名空间中。命名空间生成的,也可以理解为 命名变量。命名空间的好处,类似模块化开发的好处,能尽量少的声明全局变量,把一组相关的内容封装到一起去,对外提供统一的暴露接口。在下面中,Page 是直接暴露,其余三个是间接是间接暴露,index.html是页面,page.tsts 文件,page.js 是编译 ts 文件后生成的 js 文件,代码如下所示:

    • index.html

      <!DOCTYPE html>





      Document





    • page.ts

      namespace Home {
      class Header {

      1. constructor() {
      2. const elem = document.createElement("div");
      3. elem.innerText = "this is header";
      4. document.body.appendChild(elem);
      5. }

      }

      class Content {

      1. constructor() {
      2. const elem = document.createElement("div");
      3. elem.innerText = "this is content";
      4. document.body.appendChild(elem);
      5. }

      }

      class Footer {

      1. constructor() {
      2. const elem = document.createElement("div");
      3. elem.innerText = "this is footer";
      4. document.body.appendChild(elem);
      5. }

      }

      export class Page {

      1. constructor() {
      2. new Header();
      3. new Content();
      4. new Footer();
      5. }

      }
      }

    • page.js

      “use strict”;
      var Home;
      (function (Home) {

      1. var Header = /** @class */ (function () {
      2. function Header() {
      3. var elem = document.createElement("div");
      4. elem.innerText = "this is header";
      5. document.body.appendChild(elem);
      6. }
      7. return Header;
      8. }());
      9. var Content = /** @class */ (function () {
      10. function Content() {
      11. var elem = document.createElement("div");
      12. elem.innerText = "this is content";
      13. document.body.appendChild(elem);
      14. }
      15. return Content;
      16. }());
      17. var Footer = /** @class */ (function () {
      18. function Footer() {
      19. var elem = document.createElement("div");
      20. elem.innerText = "this is footer";
      21. document.body.appendChild(elem);
      22. }
      23. return Footer;
      24. }());
      25. var Page = /** @class */ (function () {
      26. function Page() {
      27. new Header();
      28. new Content();
      29. new Footer();
      30. }
      31. return Page;
      32. }());
      33. Home.Page = Page;

      })(Home || (Home = { }));

  3. 分离到多文件,当应用变得越来越大时,我们需要将代码分离到不同的文件中以便于维护。尽管是不同的文件,它们仍是同一个命名空间,并且在使用的时候就如同它们在一个文件中定义的一样。 因为不同文件之间存在依赖关系,所以我们加入了引用标签来告诉编译器文件之间的关联。多文件确保所有编译后的代码都被加载,有两种方式。第一种方式,把所有的输入文件编译为一个输出文件,需要使用--outFile 标记,编译器会根据源码里的引用标签自动地对输出进行排序,也可以单独地指定每个文件。第二种方式,我们可以编译每一个文件(默认方式),那么每个源文件都会对应生成一个 JavaScript 文件。 然后,在页面上通过 <script> 标签把所有生成的 JavaScript 文件按正确的顺序引进来。

  4. 如下,在子命名空间 Components 中,还可以再使用子命名空间,可以使用接口,也可以使用类。Home 的这个命名空间,依赖于 components.ts 这个文件,需要做引用标签。同时,修改 tsconfig.json 文件,修改 module、outFile、outDir 和 rootDir,代码如下所示:

    • index.html

      <!DOCTYPE html>





      Document





    • components.ts

      namespace Components {
      export namespace SubComponents {

      1. export class Test { }

      }

      export interface User {

      1. name: string;

      }

      export class Header {

      1. constructor() {
      2. const elem = document.createElement("div");
      3. elem.innerText = "this is header";
      4. document.body.appendChild(elem);
      5. }

      }

      export class Content {

      1. constructor() {
      2. const elem = document.createElement("div");
      3. elem.innerText = "this is content";
      4. document.body.appendChild(elem);
      5. }

      }

      export class Footer {

      1. constructor() {
      2. const elem = document.createElement("div");
      3. elem.innerText = "this is footer";
      4. document.body.appendChild(elem);
      5. }

      }
      }

    • page.ts

      ///

      namespace Home {
      export const people: Components.User = {

      1. name: "Tom",

      };

      export class Page {

      1. constructor() {
      2. new Components.Header();
      3. new Components.Content();
      4. new Components.Footer();
      5. }

      }
      }

    • tsconfig.json

      {
      “compilerOptions”: {

      1. /* Visit https://aka.ms/tsconfig.json to read more about this file */
      2. /* Basic Options */
      3. // "incremental": true, /* Enable incremental compilation */
      4. "target": "es5",
      5. /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
      6. "module": "amd",
      7. /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
      8. // "lib": [], /* Specify library files to be included in the compilation. */
      9. // "allowJs": true, /* Allow javascript files to be compiled. */
      10. // "checkJs": true, /* Report errors in .js files. */
      11. // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
      12. // "declaration": true, /* Generates corresponding '.d.ts' file. */
      13. // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
      14. // "sourceMap": true, /* Generates corresponding '.map' file. */
      15. "outFile": "./dist/page.js",
      16. /* Concatenate and emit output to single file. */
      17. "outDir": "./dist",
      18. /* Redirect output structure to the directory. */
      19. "rootDir": "./src",
      20. /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
      21. // "composite": true, /* Enable project compilation */
      22. // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
      23. // "removeComments": true, /* Do not emit comments to output. */
      24. // "noEmit": true, /* Do not emit outputs. */
      25. // "importHelpers": true, /* Import emit helpers from 'tslib'. */
      26. // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
      27. // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
      28. /* Strict Type-Checking Options */
      29. "strict": true,
      30. /* Enable all strict type-checking options. */
      31. // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
      32. // "strictNullChecks": true, /* Enable strict null checks. */
      33. // "strictFunctionTypes": true, /* Enable strict checking of function types. */
      34. // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
      35. // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
      36. // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
      37. // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
      38. /* Additional Checks */
      39. // "noUnusedLocals": true, /* Report errors on unused locals. */
      40. // "noUnusedParameters": true, /* Report errors on unused parameters. */
      41. // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
      42. // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
      43. /* Module Resolution Options */
      44. // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
      45. // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
      46. // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
      47. // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
      48. // "typeRoots": [], /* List of folders to include type definitions from. */
      49. // "types": [], /* Type declaration files to be included in compilation. */
      50. // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
      51. "esModuleInterop": true,
      52. /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
      53. // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
      54. // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
      55. /* Source Map Options */
      56. // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
      57. // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
      58. // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
      59. // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
      60. /* Experimental Options */
      61. // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
      62. // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
      63. /* Advanced Options */
      64. "skipLibCheck": true,
      65. /* Skip type checking of declaration files. */
      66. "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
      67. }

      }

  5. 别名,简化命名空间操作的方法,为指定的符号创建一个别名。你可以用这种方法为任意标识符创建别名,也包括导入的模块中的对象。我们使用 import 语句对模块进行拆分与组合,打包后生成 AMD 规范,代码如下所示:

    • index.html

      <!DOCTYPE html>





      Document






    • components.ts

      export class Header {
      constructor() {

      1. const elem = document.createElement("div");
      2. elem.innerText = "this is header";
      3. document.body.appendChild(elem);

      }
      }

      export class Content {
      constructor() {

      1. const elem = document.createElement("div");
      2. elem.innerText = "this is content";
      3. document.body.appendChild(elem);

      }
      }

      export class Footer {
      constructor() {

      1. const elem = document.createElement("div");
      2. elem.innerText = "this is footer";
      3. document.body.appendChild(elem);

      }
      }

    • page.ts

      import { Header, Content, Footer } from “./components”;

      class Page {
      constructor() {

      1. new Header();
      2. new Content();
      3. new Footer();

      }
      }

  6. 使用 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”: {

      1. "test": "parcel ./src/index.html"

      },
      “keywords”: [],
      “author”: “”,
      “license”: “ISC”,
      “devDependencies”: {

      1. "parcel": "^2.0.0-alpha.3.2"

      }
      }

    • tsconfig.json

      {
      “compilerOptions”: {

      1. /* Visit https://aka.ms/tsconfig.json to read more about this file */
      2. /* Basic Options */
      3. // "incremental": true, /* Enable incremental compilation */
      4. "target": "es5",
      5. /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
      6. "module": "commonjs",
      7. /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
      8. // "lib": [], /* Specify library files to be included in the compilation. */
      9. // "allowJs": true, /* Allow javascript files to be compiled. */
      10. // "checkJs": true, /* Report errors in .js files. */
      11. // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
      12. // "declaration": true, /* Generates corresponding '.d.ts' file. */
      13. // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
      14. // "sourceMap": true, /* Generates corresponding '.map' file. */
      15. // "outFile": "./", /* Concatenate and emit output to single file. */
      16. "outDir": "./dist",
      17. /* Redirect output structure to the directory. */
      18. "rootDir": "./src",
      19. /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
      20. // "composite": true, /* Enable project compilation */
      21. // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
      22. // "removeComments": true, /* Do not emit comments to output. */
      23. // "noEmit": true, /* Do not emit outputs. */
      24. // "importHelpers": true, /* Import emit helpers from 'tslib'. */
      25. // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
      26. // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
      27. /* Strict Type-Checking Options */
      28. "strict": true,
      29. /* Enable all strict type-checking options. */
      30. // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
      31. // "strictNullChecks": true, /* Enable strict null checks. */
      32. // "strictFunctionTypes": true, /* Enable strict checking of function types. */
      33. // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
      34. // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
      35. // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
      36. // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
      37. /* Additional Checks */
      38. // "noUnusedLocals": true, /* Report errors on unused locals. */
      39. // "noUnusedParameters": true, /* Report errors on unused parameters. */
      40. // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
      41. // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
      42. /* Module Resolution Options */
      43. // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
      44. // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
      45. // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
      46. // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
      47. // "typeRoots": [], /* List of folders to include type definitions from. */
      48. // "types": [], /* Type declaration files to be included in compilation. */
      49. // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
      50. "esModuleInterop": true,
      51. /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
      52. // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
      53. // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
      54. /* Source Map Options */
      55. // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
      56. // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
      57. // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
      58. // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
      59. /* Experimental Options */
      60. // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
      61. // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
      62. /* Advanced Options */
      63. "skipLibCheck": true,
      64. /* Skip type checking of declaration files. */
      65. "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */

      }
      }

二、Typescript 的描述文件

  1. 类型定义文件,帮助 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;

  2. 使用 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 {

      1. class init { }

      }
      }

      // 使用 interface 的语法,实现函数重载
      // interface JQuery {
      // (readyFunc: () => void): void;
      // (selector: string): JqueryInstance;
      // }

      // declare var $: JQuery;

  3. 对于类型描述文件,也可以使用模块化的代码,使用 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 {

      1. html: (html: string) => JqueryInstance;

      }

      function $(readyFunc: () => void): void;
      function $(selector: string): JqueryInstance;
      namespace $ {

      1. namespace fn {
      2. class init { }
      3. }

      }
      export = $;
      }

发表评论

表情:
评论列表 (有 0 条评论,26人围观)

还没有评论,来说两句吧...

相关阅读

    相关 TypeScript命名空间

    > namespace 命名空间,可以把一组全局变量封装成一个统一的接口,选择性的进行暴露,实现组件化开发思想。 > > 1. 用 namespace Home 包裹全局变

    相关 TypeScript 命名空间模块

    //命名空间namespace //创建一个命名空间,命名空间中存放的是类,是方便我们导入命名空间来调用类或者方法的 //命名空间的好处就是,让文件中的类名等不怕重复,