Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ts类库声明

文件以.d.ts结尾,替代.js即可

全局类库的声明文件

  • 原js文件

    //global-lib.js
    function globalLib(options) {
      console.log(options);
    }
    
    globalLib.version = "1.0.0";
    
    globalLib.doSomething = function () {
      console.log("global doSomething");
    };
    
  • ts声明文件

    //global-lib.d.ts
    declare function globalLib(options: globalLib.Options): void;
    
    declare namespace globalLib {
        const version: string;
        function doSomething(): void;
        interface Options {
            [key: string]: any;
        }
    }
    
  • 在 index.ts 中使用

    globalLib({ x: 1 });
    
    globalLib.doSomething();
    
  • 在 html 中使用

    
    

模块类库的声明文件

  • 原js文件

    //module-lib.js
    const version = "1.0.1";
    
    function doSomething() {
      console.log("moduleLib do something");
    }
    
    function moduleLib(options) {
      console.log(options);
    }
    
    moduleLib.version = version;
    moduleLib.doSomething = doSomething;
    
    module.exports = moduleLib;
    
  • ts声明文件

    //module-lib.d.ts
    declare function moduleLib(options: Options): void;
    
    interface Options {
        [key: string]: any;
    }
    
    declare namespace moduleLib {
        const version: string;
        function doSomething(): void;
    }
    
    export = moduleLib;
    
  • 在 index.ts 中使用

    import moduleLib from "./module-lib";
    
    moduleLib.doSomething();
    

UMD类库的声明文件

  • 原js代码

    // umd-lib.js
    (function (root, factory) {
      if (typeof define === "function" && define.amd) {
        define(factory);
      } else if (typeof module === "object" && module.exports) {
        module.exports = factory();
      } else {
        root.umdLib = factory();
      }
    })(this, function () {
      return {
        version: "1.0.1",
        doSomething() {
          console.log("umdLib do Something");
        },
      };
    });
    
  • ts声明文件

    declare namespace umdLib {
        const version: string;
        function doSomething(): void;
    }
    export as namespace umdLib;
    
    export = umdLib;
    
  • 在 index.ts 中使用

    import umdLib from "./umd-lib";
    
    umdLib.doSomething();
    
  • 也可以通过全局的方式引用

    • 需要修改 tsconfig.json 配置
      "allowUmdGlobalAccess": true,
      
    • 在 html 中引用
      <script src="/src/libs/umd-lib.js"></script>
      
    • 然后使用
      umdLib.doSomething();