【问题标题】:Typescript: how to import class that was exported using `export = uuid`打字稿:如何导入使用`export = uuid`导出的类
【发布时间】:2018-07-08 12:58:18
【问题描述】:

我正在尝试在打字稿中使用 node_module uuid-js。我已经安装了模块和打字。

问题:如何导入模块?


我要使用的方法是uuid.create

这是在uuid-js 的输入中定义的,如下所示:

export = uuid;
declare class uuid {
    equals(uuid: uuid): boolean;
    ... 
    static create(version?: number): uuid;
    ...
}

typescript doc 说:

使用 export = 导入模块时,TypeScript 特定的导入 module = require("module") 必须用于导入模块。

这似乎暗示我需要这样做:

import UUID = require('uuid-js');

这似乎编译成这样:

const UUID = require("uuid-js")  

我是否有理由在我的代码中使用 import 而不是 const?为什么不直接使用编译好的代码呢?

我觉得使用 require 很奇怪。也许,我不使用打字或做其他事情会更好......?

使用有什么区别:

import UUID = require('uuid-js');

const UUID = require("uuid-js")  

我也尝试过像宇智波斑建议的那样使用更传统的导入策略,但我得到了错误。

使用import * as UUID from 'uuid-js' 会导致:

error TS2497: Module '".../node_modules/@types/uuid-js/index"' resolves to a non-module entity and cannot be imported using this construct.

使用import UUID from 'uuid-js'; 会导致:

error TS1192: Module '".../node_modules/@types/uuid-js/index"' has no default export.

【问题讨论】:

  • 据匿名消息人士称,导入语法是 TS 发明的遗留语法,不应再使用
  • @SterlingArcher - 应该使用什么?

标签: typescript import


【解决方案1】:

import something = require('something')export = something 都是 TypeScript 在 ES2015 模块出现之前发明的遗留语法。

现在,我们使用标准模块语法,如下所示:

import * as UUID from 'uuid-js'; // if uuid-js has no export default
// or
import UUID from 'uuid-js'; // if it does.

您提出的类型 sn-p 表明您应该使用前者。

【讨论】:

  • 我也试过了,但运气有限。我更新了我的问题以提供更多信息。
【解决方案2】:

这些有何不同

import 还导入 类型const/require 没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-19
    • 2012-12-26
    • 2017-02-06
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    相关资源
    最近更新 更多