如何使用 typescript 导入 moment.js?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36648231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:04:13  来源:igfitidea点击:

How can moment.js be imported with typescript?

typescriptmomentjsjspm

提问by peinearydevelopment

I'm trying to learn Typescript. While I don't think it's relevant, I'm using VSCode for this demo.

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

I have a package.jsonthat has these pieces in it:

我有一个里面package.json有这些片段:

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

Then I have a Typescript class main.jslike this:

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

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

My gulpfile.jslooks like this:

我的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'));
});

When I run gulp build, I get the message: "../main.ts(1,25): Cannot file module 'moment'."

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

If I use import moment = require('moment');then jspm will work and bring in the module when I run the application, but I'm still receiving the build error. I also tried:

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

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

Instead of making the problem better though, it got worse. Now I get the above error on build as well as the following: "../typings/browser/ambient/moment/index.d.ts(9,21): Cannot find namespace 'moment'."

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

If I go to the file provided by typings and add at the bottom of the file:

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

declare module "moment" { export = moment; }

I can get the second error to go away, but I still need the require statement to get moment to work in my main.tsfile and am still getting the first build error.

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

Do I need to create my own .d.tsfile for moment or is there just some setup piece I'm missing?

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

回答by Aides

Update

更新

Apparently, moment now provides its own type definitions (according to sivabudhat least from 2.14.1 upwards), thus you do not need typingsor @typesat all.

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

import * as moment from 'moment'should load the type definitions provided with the npm package.

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

That said however, as said in moment/pull/3319#issuecomment-263752265the moment team seems to have some issues in maintaining those definitions (they are still searching someone who maintains them).

然而,正如在moment/pull/3319#issuecomment-263752265 中所说的那样,moment 团队似乎在维护这些定义方面存在一些问题(他们仍在寻找维护它们的人)



You need to install momenttypings without the --ambientflag.

您需要安装moment没有--ambient标志的类型。

Then include it using import * as moment from 'moment'

然后使用它包含它 import * as moment from 'moment'

回答by Koby

You need to import moment()the function and Momentthe class separately in TS.

您需要在 TS 中分别导入moment()函数和Moment类。

I found a note in the typescript docs here.

我在此处的打字稿文档中找到了一条注释。

/*~ Note that ES6 modules cannot directly export callable functions
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');

/*~ 注意 ES6 模块不能直接导出可调用函数
*~ 这个文件应该使用 CommonJS 风格
导入:*~ import x = require('someLibrary');

So the code to import moment js into typescript actually looks like this:

所以将 moment js 导入 typescript 的代码实际上是这样的:

import { Moment } from 'moment'
....
let moment = require('moment');
...
interface SomeTime {
  aMoment: Moment,
}
...
fn() {
  ...
  someTime.aMoment = moment(...);
  ...
}

回答by NSjonas

Not sure when this changed, but with the latest version of typescript, you just need to use import moment from 'moment';and everything else should work as normal.

不确定何时更改,但使用最新版本的打字稿,您只需要使用import moment from 'moment';,其他一切都应该正常工作。

UPDATE:

更新:

Looks like moment recent fixed their import. As of at least 2.24.0you'll want to use import * as moment from 'moment';

看起来最近修复了他们的进口。至少2.24.0你会想要使用import * as moment from 'moment';

回答by sivabudh

via typings

通过打字

Moment.js now supports TypeScript in v2.14.1.

Moment.js 现在在 v2.14.1 中支持 TypeScript。

See: https://github.com/moment/moment/pull/3280

见:https: //github.com/moment/moment/pull/3280



Directly

直接地

Might not be the best answer, but this is the brute force way, and it works for me.

可能不是最好的答案,但这是蛮力的方式,它对我有用。

  1. Just download the actual moment.jsfile and include it in your project.
  2. For example, my project looks like this:
  1. 只需下载实际moment.js文件并将其包含在您的项目中。
  2. 例如,我的项目如下所示:

$ tree . ├── main.js ├── main.js.map ├── main.ts └── moment.js

$ tree . ├── main.js ├── main.js.map ├── main.ts └── moment.js

  1. And here's a sample source code:
  1. 这是一个示例源代码:

```

``

import * as moment from 'moment';

class HelloWorld {
    public hello(input:string):string {
        if (input === '') {
            return "Hello, World!";
        }
        else {
            return "Hello, " + input + "!";
        }
    }
}

let h = new HelloWorld();
console.log(moment().format('YYYY-MM-DD HH:mm:ss'));
  1. Just use nodeto run main.js.
  1. 只是node用来运行main.js

回答by hardy lutula

1. install moment

1.安装时刻

npm install moment --save

2. test this code in your typescript file

2. 在您的打字稿文件中测试此代码

import moment = require('moment');

console.log(moment().format('LLLL'));

回答by Mark Birbeck

I've just noticed that the answer that I upvoted and commented on is ambiguous. So the following is exactly what worked for me. I'm currently on Moment 2.26.0and TS 3.8.3:

我刚刚注意到我赞成和评论的答案是模棱两可的。所以以下正是对我有用的。我目前在 Moment2.26.0和 TS 上3.8.3

In code:

在代码中:

import moment from 'moment';

In TS config:

在 TS 配置中:

{
  "compilerOptions": {
    "esModuleInterop": true,
    ...
  }
}

I am building for bothCommonJS and EMS so this config is imported into other config files.

我建立了所以这个配置导入到其他配置文件CommonJS的和EMS。

The insight comes from this answerwhich relates to using Express. I figured it was worth adding here though, to help anyone who searches in relation to Moment.js, rather than something more general.

洞察力来自与使用 Express 相关的答案。我认为值得在这里添加,以帮助任何与 Moment.js 相关的搜索,而不是更一般的东西。