gpt4 book ai didi

typescript - moment.js 如何用 typescript 导入?

转载 作者:搜寻专家 更新时间:2023-10-30 20:28:53 26 4
gpt4 key购买 nike

我正在尝试学习 typescript 。虽然我认为这无关紧要,但我在这个演示中使用了 VSCode。

我有一个包含这些部分的 package.json:

{
"devDependencies": {
"gulp": "^3.9.1",
"jspm": "^0.16.33",
"typescript": "^1.8.10"
},
"jspm": {
"moment": "npm:moment@^2.12.0"
}
}

然后我有一个像这样的 Typescript 类 main.js:

import moment from 'moment';
export class Main {
}

我的 gulpfile.js 看起来像这样:

var gulp = require('gulp');
var typescript = require('gulp-tsb');
var compilerOptions = {
"rootDir": "src/",
"sourceMap": true,
"target": "es5",
"module": "amd",
"declaration": false,
"noImplicitAny": false,
"noResolve": true,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
};
var typescriptCompiler = typescript.create(compilerOptions);
gulp.task('build', function() {
return gulp.src('/src')
.pipe(typescriptCompiler())
.pipe(gulp.dest('/dest'));
});

当我运行 gulp build 时,我收到消息:"../main.ts(1,25): Cannot file module 'moment'."

如果我使用 import moment = require('moment'); 那么当我运行应用程序时 jspm 将工作并引入模块,但我仍然收到构建错误。我也试过:

npm install typings -g
typings install moment --ambient --save

问题没有好转,反而变得更糟。现在,我在构建时遇到了上述错误以及以下错误:"../typings/browser/ambient/moment/index.d.ts(9,21): Cannot find namespace 'moment'."

如果我转到 typings 提供的文件并在文件底部添加:

declare module "moment" { export = moment; }

我可以让第二个错误消失,但我仍然需要 require 语句才能在我的 main.ts 文件中工作,并且仍然遇到第一个构建错误。

我是否需要暂时创建自己的 .d.ts 文件,还是只是缺少一些设置?

最佳答案

更新

显然,moment 现在提供了自己的类型定义(根据 sivabudh 至少从 2.14.1 开始),因此您不需要 typings@types完全没有。

import * as moment from 'moment' 应该加载 npm 包提供的类型定义。

然而,如 moment/pull/3319#issuecomment-263752265 中所述目前团队似乎在维护这些定义方面遇到了一些问题(他们仍在寻找维护它们的人)


您需要安装不带 --ambient 标志的 moment 类型。

然后使用 import * as moment from 'moment' 将其包含在内

关于typescript - moment.js 如何用 typescript 导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36648231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com