【问题标题】:How should i organize typescript modules/packages using tsd typings?我应该如何使用 tsd 类型组织打字稿模块/包?
【发布时间】:2016-03-15 23:51:01
【问题描述】:

我有一个相当大的 TS 项目,其中包含许多作为 npm 包相互链接的内部库。 有时在 .ts 中,我需要引用 TSD 提供的一些环境或外部定义,如下所示: /// <reference path="../../typings/tsd.d.ts" /> 每个包都包含引用...root.../typings/tsd.d.ts 的自己的.d.ts 文件。

因此,当我在另一个依赖包中安装依赖包时,可以对一些环境内容进行多重定义,例如...root.../typings/node/node.d.t。它会导致编译错误Duplicate identifier

我想你们都知道这个问题。但是我花了大约一天的时间在谷歌上搜索、阅读并尝试了许多无法正常工作的解决方案。 :(

请告诉我一条出路。告诉我你是怎么做到的。

【问题讨论】:

    标签: node.js typescript definitelytyped


    【解决方案1】:

    嗯……一个奇怪的想法来了。 在所有项目中放入一个 postinstall 挂钩脚本,该脚本更改 typings/tsd.d.ts 并将复制定义文件的路径替换为父项目的路径,如下所示:/// <reference path="../../../../typings/node/node.d.ts" />

    它很脏,但可以正常工作

    var fs = require('fs');
    var path = require('path');
    
    
    
    function searchParentTypingPath(currentPath, moduleName, depth){
        if (!depth) depth = 1;
        if (depth>4) return null;
        try{
            var filePath = currentPath+'/typings/'+moduleName+'/'+moduleName+'.d.ts';
            fs.accessSync(filePath);
            return filePath;
        }
        catch(e){
            return searchParentTypingPath(currentPath+'/..', moduleName, depth+1);
        }
    }
    
    
    module.exports = function (tsdFilePath, verbose){
        var tsdContent = fs.readFileSync(tsdFilePath).toString();
        var resultContent = '';
        tsdContent.split('\n').forEach(function(line){
            var match = line.match(/^\/\/\/\s+<reference path="([\/a-zA-Z0-9_\-.]+)"\s*\/>/);
            if (!match) {
                resultContent+=line+'\n';
                return;
            }
            var modulePath = match[1];
            if (!modulePath.match(/^\w+/)) {// it's not provided by TSD
                resultContent+=line+'\n';
                return;
            }
            var moduleName =  path.basename(modulePath, '.d.ts');
    
            var parentPath = searchParentTypingPath(path.dirname(tsdFilePath)+'/../..', moduleName);
            resultContent+='/// <reference path="'+(parentPath||modulePath)+'" />\n';
        });
        if (verbose) {
            console.log(resultContent);
            return resultContent;
        }
        fs.writeFileSync(tsdFilePath, resultContent);
    };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 2017-08-07
      • 2018-02-24
      • 2021-07-06
      • 2020-04-17
      相关资源
      最近更新 更多