我正在将一个网站转换为使用 TypeScript,我只是将许多 JavaScript 文件中的一个转换为 TypeScript。 我网站的所有页面都已经引用了 moment.js,例如:
<script src="/scripts/moment.min.js"></script>
我使用以下方式添加了其他 TypeScript 定义文件:
npm install --save-dev @types/jquery
...但是,上面的选择暂时似乎是错误的。当我使用上述命令时(但用“moment”代替“jquery”),会下载一个自述文件,上面写着:
This is a stub types definition for Moment (https://github.com/moment/moment). Moment provides its own type definitions, so you don't need @types/moment installed!
作为解决方案,我尝试从 GitHub 存储库中保存 moment.d.ts 文件,并在 TypeScript 文件中引用它:
///<reference path="../../Scripts/typeDeclarations/moment.d.ts"/>
var now:any = moment.utc();
但是,TypeScript 给了我警告:
Cannot find the name 'moment'
最佳答案
TL;DR;
添加 moment.d.ts
( link ) 从 github 站点开始在你的项目中 注释掉 最后一行
//export = moment;
我已经创建了一个小型测试项目来证明这一点并且这对我有用。
项目结构
--
|
-typings/
-moment/
-moment.d.ts <-- //export = moment; commented out
-typescript/
-main.ts
-tsconfig.json
两者的内容typings
和 typescript
是编译目标的一部分,即未排除在 tsconfig.json
中看起来像这样
{
"compilerOptions": {
"target": "es5",
"declaration": false,
"noImplicitAny": true,
"removeComments": true,
"outDir": "dist",
"jsx": "react",
"sourceMap": true,
"experimentalDecorators": true
},
"compileOnSave": true,
"exclude": [
"node_modules",
"dist"
]
}
main.ts
文件包含
const now: moment.Moment = moment.utc();
并编译... 正如预期的那样,我的 IDE 使我可以从定义文件自动完成。
(不需要 ///<reference
标签——无论如何你都应该避免使用它们)
删除 export
定义文件末尾的语句,将其“转换”为内部 - 但全局 - 模块声明文件。
关于typescript - 如果我的网站已经在使用 moment.min.js,如何使用 Moment.js TypeScript 定义文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42234096/