【问题标题】:Node TypeScript import/export mechanics节点 TypeScript 导入/导出机制
【发布时间】:2020-10-01 06:55:00
【问题描述】:

我对 WebStorm 中的 TypeScript 导入/导出机制有疑问。 可以说,我有一个名为 apiUtils.ts 的文件:

export function getUsername(req) {
    return req.headers.username;
}

export default module.exports;

我还有另一个文件,即引用 apiUtils.ts:

import apiUtils from "../bin/apiUtils";

const req = '';
const username = apiUtils.getUsername(req);

getUsername 方法未即时识别,我无法使用 Ctrl + 单击 导航到该方法。它被标记为未使用,我什至可以编写以下代码并成功编译代码而不会收到错误:

import apiUtils from "../bin/apiUtils";

const req = '';
const username = apiUtils.getUsername(req, thereIsNoSecontArgInThisMehod);

另一方面,如果我按如下方式导入方法:

import { getUsername } from "../bin/apiUtils";

const req = '';
const username = getUsername(req);

一切都会按预期工作:我得到导航、输入验证等。

我更喜欢使用import apiUtils from "../bin/apiUtils";,而不是单独导入每个方法,因为它会造成方法混乱,不清楚它们属于哪里,是否是本地的。

有没有办法修复导入,并让它了解引用了什么方法?因为对于运行时来说,这两种方式都是一样的。

【问题讨论】:

    标签: node.js typescript import webstorm


    【解决方案1】:

    这是由于export default module.exports 构造而发生的——我所知道的所有 IDE 都无法处理它们。

    如果您想导入整个模块,请使用import * as <name> 构造(https://www.typescriptlang.org/docs/handbook/modules.html#import-the-entire-module-into-a-single-variable-and-use-it-to-access-the-module-exports):

    export function getUsername(req) {
        return req.headers.username;
    }
    
    import * as apiUtils from "../bin/apiUtils";
    
    const req = '';
    const username = apiUtils.getUsername(req);
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 2012-11-03
      • 2013-08-25
      • 2017-04-03
      • 1970-01-01
      • 2017-06-19
      • 2022-07-25
      相关资源
      最近更新 更多