从已安装的@types导入? [英] Import from installed @types?

查看:345
本文介绍了从已安装的@types导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经安装了md5(也尝试过blueimp-md5)程序包,其类型如下:

I've installed md5 (also tried blueimp-md5) package with corresponding typings like this:

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中,我有:

This makes me think that installed @types/md5 typings are simply not discovered. In tsconfig.json I have:

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

因此,我认为它应该自动检测node_modules/@types文件夹中的类型,但显然不能.与blueimp-md5包完全相同. md5文件夹位于node_modules/@types文件夹中,因此具有所有内容,但仍然无法使用.

So I think it should be detecting typings from node_modules/@types folder automatically, but it apparently does not. Exactly same thing with blueimp-md5 package. The md5 folder exists in node_modules/@types folder, so it has everything in place but still doesn't work.

Visual Studio代码,TypeScript 2,Angular 2项目.

Visual Studio Code, TypeScript 2, Angular 2 project.

我在做什么错了?

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

this is content of @types/md5/index.d.ts file:

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

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

推荐答案

您无需指定node_modules内部的路径,它应该是:

You don't need to specify the path inside the node_modules, it should be:

import * as md5 from "md5";

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

The compiler will look for the actual module in the node_modules, and will look for the definition files in node_modules/@types.

关于它的文档页面很长:模块分辨率

There's a long doc page about it: Module Resolution

这是因为md5模块的导出方式,因为它这样做:

That's because of how the md5 module is exporting, as it does this:

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

这种情况是在文档中发现的 :

This case is covered in the docs:

export =语法指定从中导出的单个对象 模块.这可以是类,接口,名称空间,函数或 枚举.

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.

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

When importing a module using export =, TypeScript-specific import let = require("module") must be used to import the module.

您的情况应该是:

import md5 = require("md5");


第二次修改

如果您要定位es6,则需要执行以下操作:


2nd edit

If you're targetting es6 then you need to do:

const md5 = require("md5");

(当然是letvar).

这篇关于从已安装的@types导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆