从已安装的@types导入? [英] Import from installed @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");
(当然是let
或var
).
这篇关于从已安装的@types导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!