【问题标题】:How to use typescript triple-slash reference comments to import another module and use the functions?如何使用打字稿三斜杠参考注释导入另一个模块并使用功能?
【发布时间】:2019-01-15 16:28:32
【问题描述】:

现在可能不需要Typescript的三斜杠引用,但我还是想知道怎么用。

假设我有两个文件:

--模块/ad.ts

export declare function hello(name: any): void;

-- 模块/a.js

"use strict";
exports.__esModule = true;
function hello(name) {
    console.log("Hello, " + name + " (from a)");
}
exports.hello = hello;

现在我想在另一个打字稿文件中使用它:

你好.ts

/// <reference path="./modules/a.d.ts" />

hello("module a");

我是这样写的,但是编译hello.ts的时候报错:

hello.ts(3,1): error TS2304: Cannot find name 'hello'.

我该如何解决?

【问题讨论】:

    标签: typescript import module


    【解决方案1】:

    看来我对模块有很多误解。

    为了让一切正常,我必须进行以下更改:

    修改modules/a.d.ts

    declare module 'a' {
        export function hello(name: string) : void;
    }
    

    它应该声明 module 'a' 以便与 /// &lt;reference ... 一起工作

    使 modules/a.js 成为本地 npm 包

    modules 目录中提供package.json,内容:

    {
      "name": "a",
      "version": "1.0.0",
      "main": "a.js"
    }
    

    然后安装它npm install --save ./modules

    最后,下面的代码可以工作了

    /// <reference path="./modules/a.d.ts" />
    import {hello} from 'a';
    
    hello("typescript");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 2015-05-09
      • 2020-02-05
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      相关资源
      最近更新 更多