如何使用TypeScript对使用Moment的.js文件进行类型检查? [英] How to typecheck a .js file that uses Moment using TypeScript?
问题描述
我有一个使用Moment的小.js文件,该文件旨在直接在要使用TypeScript编译器进行类型检查的浏览器中运行:
I have a small .js file using Moment intended to be run directly in a browser that I want to be type-checked with the TypeScript compiler:
document.querySelector("body").textContent = moment().toString();
如果我尝试使用tsc
进行类型检查,则编译器会抱怨,即使我安装了moment
npm软件包,也无法找到moment
的声明:
If I try to typecheck it with tsc
, the compiler complains it cannot find the declaration for moment
even though I have the moment
npm package installed:
$ npm install typescript moment
$ node_modules/.bin/tsc --allowJs --checkJs --noEmit index.js
index.js:1:46 - error TS2304: Cannot find name 'moment'.
1 document.querySelector("body").textContent = moment().toString();
~~~~~~
Found 1 error.
如何告诉TypeScript编译器自动检测moment
全局对象或将其显式导入JS文件中?
How do I tell the TypeScript compiler to auto-detect the moment
global object or to import it explicitly in the JS file?
推荐答案
暂时< = 2.24.0
使用内容创建文件moment.shims.d.ts
import moment from '../../node_modules/moment/moment';
export = moment;
export as namespace moment;
(更改导入行以指向您在node_modules中安装的moment的版本.)
(Alter the import line to point to your installed version of moment in node_modules.)
与您的TypeScript项目的其余部分一起编译此shims文件.
Compile this shims file alongside the rest of your TypeScript project.
您可能需要在tsconfig.json
或对tsc --esModuleInterop true
的调用中启用esModuleInterop
选项:
You may need to enable the esModuleInterop
option in your tsconfig.json
or in your call to tsc --esModuleInterop true
:
{
...
"compilerOptions": {
...
"esModuleInterop": true, // needed by: moment.shims.d.ts
},
}
暂时> 2.24.0
此PR 被接受后,无需采取特殊措施.
For moment > 2.24.0
No special action required, once this PR is accepted.
这篇关于如何使用TypeScript对使用Moment的.js文件进行类型检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!