Moment.js + TypeScript.找不到名字的时刻

use*_*018 10 module momentjs typescript

我在VisualStudio中使用knockout开发Web应用程序.我刚刚通过bower安装了淘汰赛,包括项目中的d.ts文件,包含脚本到html页面,现在我可以访问了ko.

现在我尝试使用moment.js.与淘汰赛一样:安装,包括d.ts,包括脚本到页面,我收到一个错误cannot find name 'moment'.添加对d.ts的引用没有帮助,import * as moment from 'moment'得到一个错误can not find module moment.

我知道这是一个愚蠢的问题,但我无法解决它.我究竟做错了什么?

Bal*_*des 11

我建议使用一些工具来管理你的定义.一些流行的选项(你不需要两个,只需选择一个):

  1. tsd - npm i -g tsd
  2. typings - npm i -g typings

这些工作方式与包管理器类似.你可以安装你的定义,如npm/bower安装你的依赖项.

一旦安装了其中一个,请转到您的项目并安装时刻+其定义

npm install moment --save
Run Code Online (Sandbox Code Playgroud)

其中一个:

tsd install moment --save
typings install moment --save --ambient
Run Code Online (Sandbox Code Playgroud)

这两个都将创建一个包含您的定义的文件夹(两者都称之为打字),并且两者都有一个"伞"定义文件,您应该在应用程序的入口点引用(首先是tsd,第二个是分型):

/// <reference path="typings/tsd.d.ts" />
/// <reference path="typings/index.d.ts" />
Run Code Online (Sandbox Code Playgroud)

完成此操作后,您可以使用时刻(或任何其他模块):

import * as moment from 'moment'
moment.isDate("I'm not a date")
Run Code Online (Sandbox Code Playgroud)

我建议看看这些:

https://github.com/DefinitelyTyped/tsd
https://github.com/typings/typings

  • 从TypeScript 2.0开始,可以在没有“ tsd”或“ typings”的情况下完成此操作,请参阅:https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/ (2认同)

Raú*_*año 7

在我的情况下,最后通过执行以下操作来解决此错误:

  1. 在文件"allowSyntheticDefaultImports": true,compilerOptions部分添加此选项tsconfig.json(EDITED:作为注释中时刻 doc.sais ) If you have trouble importing moment, try add "allowSyntheticDefaultImports": true in compilerOptions in your tsconfig.json file.
  2. 同时添加"moduleResolution": "node"相同的compilerOptions部分.(发现这个选项环顾网络)
  3. 像这样导入时刻模块 import * as moment from 'moment';

  • 谢谢.我在文档中找到了(1),但就其本身来说,这还不够 - 一旦我完成了(2)它就开始工作了. (2认同)

小智 7

我今天有同样的错误。修复是将 package.json 中的“moment”包从“2.25.0”降级到“2.22.1”

我的应用程序是 angular 8 版本和“打字稿”:“3.5.3

  • 谢谢,我对此失去了理智。降级解决方法对我有用 (2认同)

Sam*_*mih 5

这似乎为我解决了问题(该线程中的其他解决方案不起作用):

import * as moment from 'moment/moment.js';

即使直接引用 js 文件,我似乎仍然获得了正确的打字稿定义。我怀疑原因是 node_modules 下的“moment”文件夹没有 index.js 文件,但我不是打字稿打字/编译专家。


Syl*_*rbe 5

对我来说,错误来自于 2.25.0 版本。目前的解决方法是降级到 2.24.0。

在 moment@2.25.0 - package.json 中:

"typesVersions": {
    ">=3.1": {
      "*": [
        "ts3.1-typings/*"
      ]
    }
  }
Run Code Online (Sandbox Code Playgroud)

但是文件夹“ts3.1-typings”不存在。如果您的打字稿版本为 3.1 或更高版本,则会出现错误:

Cannot find module 'moment'
Run Code Online (Sandbox Code Playgroud)

Github 问题:https : //github.com/moment/moment/issues/5486