【问题标题】:Import from installed @types?从已安装的@types 导入?
【发布时间】:2017-05-06 04:30:23
【问题描述】:

我已经安装了md5(也试过blueimp-md5)包,对应的类型如下:

nmp install --save md5 @types/md5

nmp install --save blueimp-md5 @types/blueimp-md5

当我尝试像这样导入它时:

import { md5 } from '../../../node_modules/md5'

我收到一个错误:Module <path> was resolved to <path>/md5.js, but '--allowJs' is not set.

这让我觉得安装的@types/md5 类型根本没有被发现。 在 tsconfig.json 我有:

"typeRoots": [
  "../node_modules/@types"
]

所以我认为它应该自动检测来自node_modules/@types 文件夹的类型,但它显然没有。与blueimp-md5 包完全相同。 md5 文件夹存在于 node_modules/@types 文件夹中,因此它已准备好一切,但仍然无法正常工作。

Visual Studio Code、TypeScript 2、Angular 2 项目。

我做错了什么?

编辑:这是@types/md5/index.d.ts 文件的内容:

/// <reference types="node" />

declare function main(message: string | Buffer): string;
export = main;

【问题讨论】:

  • types文件夹的index.d.ts中是否设置了参考路径?应该有一堆这样的行: ///
  • @deek 请查看我的编辑。这让我抓狂,请帮忙!

标签: angular typescript visual-studio-code


【解决方案1】:

node_modules里面的路径不用指定,应该是:

import * as md5 from "md5";

编译器将在node_modules 中查找实际模块,并将在node_modules/@types 中查找定义文件。

有一个很长的文档页面:Module Resolution


编辑

这是因为 md5 模块是如何导出的,因为它是这样做的:

declare function main(message: string | Buffer): string;
export = main;

这个案例是covered in the docs:

export = 语法指定从 模块。这可以是类、接口、命名空间、函数或 枚举。

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

在你的情况下应该是:

import md5 = require("md5");

第二次编辑

如果您的目标是 es6,那么您需要这样做:

const md5 = require("md5");

(当然是letvar)。

【讨论】:

  • 当我只指定“md5”时,它会给出错误:Module '"&lt;path&gt;/node_modules/@types/md5/index"' resolves to a non-module entity and cannot be imported using this construct.
  • @Titan &lt;path&gt; 是什么?您是否将 TS 配置为使用节点作为模块解析?
  • 检查我修改后的答案
  • 当我使用import md5 = require("md5"); 语法时,我得到这个错误:Import assignment cannot be used when targeting ECMAScript 2015 modules.
  • 好吧,我最终使用了一个专门为 TS 编码的不同模块,并像这样导入它:import { Md5 } from 'ts-md5/dist/md5'。但我接受你对任何未来读者的回答。
猜你喜欢
  • 2018-03-16
  • 2020-04-17
  • 2018-12-12
  • 1970-01-01
  • 2020-12-02
  • 2019-10-07
  • 2021-04-29
  • 2022-11-10
  • 2020-07-05
相关资源
最近更新 更多