美文网首页
05|如何编写声明文件

05|如何编写声明文件

作者: 雪燃归来 | 来源:发表于2020-05-18 18:49 被阅读0次

    一、编写全局声明文件

    global-lib.js

    function globalLib(options){
        console.log(options);
    }
    
    globalLib.version = '1.0.0';
    
    globalLib.dosomething = function(){
        console.log('global do something')
    }
    

    global-lib.d.js

    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()
    

    二、编写commonJS声明文件

    module-lib.js

    const version = "1.01";
    
    function doSomething(){
        console.log('moduleLib do something!')
    }
    
    function moduleLib(options){
        console.log(options)
    }
    
    moduleLib.version = version;
    moduleLib.doSomething = doSomething;
    
    module.export = moduleLib;
    

    module-lib.d.js

    declare function moduleLib(options:Options):void
    
    interface Options{
        [key: number]: any
    }
    
    declare namespace moduleLib{
        const version:string;
        function doSomething():void
    }
    
    export = moduleLib
    

    index.ts

    import moduleLib from './module-lib'
    moduleLib.doSomething()
    

    三、编写umd声明文件

    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('umd module do somethig')
            }
        }
    }))
    

    umd-lib.d.ts

    declare namespace umdLib{
        const version:string
        function dosomething():void
    }
    
    export as namespace umdLib
    export = umdLib
    

    index.ts

    import umdLib from './ums-lib'
    umdLib.dosomething()
    

    三、模块化插件

    给外部的类库扩展一些方法

    import m from 'moment'
    declare module 'moment'{
        export function myFunction():void
    }
    m.myFunction = () => {}
    

    四、给全局变量增加变量和方法

    不推荐这么使用

    declare global{
        namespace globalLib{
            function doAnything():void
        }
    }
    globalLib.doAnything = () => {}
    

    相关文章

      网友评论

          本文标题:05|如何编写声明文件

          本文链接:https://www.haomeiwen.com/subject/wsxpohtx.html