当前位置: 动力学知识库 > 问答 > 编程问答 >

angular2 - Import from installed @types?

问题描述:

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

When I try to import it like this:

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

I get an error: Module <path> was resolved to <path>/md5.js, but '--allowJs' is not set.

This makes me think that installed @types/md5 typings are simply not discovered.

In tsconfig.json I have:

"typeRoots": [

"../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 Code, TypeScript 2, Angular 2 project.

What am I doing wrong?

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

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

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

export = main;

网友答案:

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

import * as md5 from "md5";

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


Edit

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:

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

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

In your case it should be:

import md5 = require("md5");

2nd edit

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

const md5 = require("md5");

(or let or var of course).

分享给朋友:
您可能感兴趣的文章:
随机阅读: