简体   繁体   English

TypeScript不会解析外部模块(node.js)

[英]TypeScript won't resolve external module (node.js)

I would like to use moment.js in my node application, so I installed moment.js using node's package manager npm: 我想在我的节点应用程序中使用moment.js,所以我使用node的包管理器npm安装了moment.js:

npm install moment@2.4.0

Just to be on the safe side, I checked moment is not installed globally and the installed version is really version 2.4.0 (version 2.4.0 in order to use the correct d.ts file ...) 只是为了安全起见,我检查时刻未全局安装,安装的版本确实是版本2.4.0(版本2.4.0以便使用正确的d.ts文件...)

require("moment").version

Alright, seems to be good. 好吧,似乎很好。 I'm also using the latest version of TypeScript (0.9.5). 我也在使用最新版本的TypeScript(0.9.5)。

So, now I added the following file to my projects root directory https://github.com/borisyankov/DefinitelyTyped/blob/master/moment/moment.d.ts and refernced the file: 所以,现在我将以下文件添加到我的项目根目录https://github.com/borisyankov/DefinitelyTyped/blob/master/moment/moment.d.ts并引用该文件:

/// <reference path="moment.d.ts" />

Now, it should work to import moment using TypeScripts import keyword: 现在,它应该使用TypeScripts import关键字导入时刻:

import m = require("moment");

Compiling with the following command 使用以下命令进行编译

tsc app.ts --module commonjs

produces the following errors 产生以下错误

/home/unknown/temp/test/app.ts(3,1): error TS2071: Unable to resolve external module '"moment"'. /home/unknown/temp/test/app.ts(3,1):错误TS2071:无法解析外部模块'“时刻”'。 /home/unknown/temp/test/app.ts(3,1): error TS2072: Module cannot be aliased to a non-module type. /home/unknown/temp/test/app.ts(3,1):错误TS2072:模块不能别名为非模块类型。

Why does this error occur? 为什么会出现此错误? How do I fix it? 我如何解决它?

The important line in the d.ts file is this one... d.ts文件中的重要一行就是这一行......

declare var moment: MomentStatic;

It just declares a variable for moment. 它只是暂时声明一个变量。

You can add the following line to resolve your problem: 您可以添加以下行来解决您的问题:

export = moment;

This should make it loadable using the import statement you have. 这应该使用您拥有的import语句使其可加载。

If you do this - you won't need yhe reference comment. 如果你这样做 - 你将不需要参考评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM