如何将 date-fns 与 TypeScript 一起使用?

How do I use date-fns with TypeScript?

我有一个使用 TypeScript 的 ASP.NET 核心网站。我的 ASP.NET 核心设置很典型,因为它在项目的根目录中有一个 node_modules 文件夹,然后我将我正在使用的库的源文件夹从 node_modules 复制到 wwwroot/lib 使用 Gulp.

因此,我在 wwwroot/lib/date-fns 和我的 TypeScript .ts 文件中有 date-fns 源文件,我正在尝试像这样导入它:

import * as fns from "lib/date-fns/i.am.stuck.here.js";

VS2019 代码编辑器正在自动完成文件夹,因此它可以看到它,但我不知道要输入什么 .js 文件,它没有建议。

我也不知道我是否应该导入 * 或其他东西。我不是前端开发人员,所以我在 TS 和 JS 以及导入和要求等方面苦苦挣扎。

我可以看到 date-fns 有一个 typings 文件,所以我认为这对知情者来说是直截了当的。


更新:

我找到了这个:

https://github.com/date-fns/date-fns/blob/master/examples/typescript/example.ts

这很奇怪,因为将我的代码更新为以下内容,这是编辑器读取磁盘上的文件夹时自动建议的:

import { format } from "lib/date-fns";

给我留下错误:

error TS2307: Cannot find module 'lib/date-fns' or its corresponding type declarations.

当我导入 moment.js 时,我将其指向自动建议的 .js 文件本身。

此外,如果我更改为 'lib/date-not-exist',我会得到同样的错误,所以我无法判断这是文件路径存在问题还是 TypeScript 定位模块问题。


更新:

我可以让 TypeScript 消除错误,大概可以找到一个模块:

import * as dformat from "lib/date-fns/format/index";

但这行不通,因为:

var result = dformat(date, 'dd.MM.yyy HH:mm:ss');

给出错误:

error TS2349: This expression is not callable.

如果您通常在浏览器中使用 TypeScript 和 JavaScript 导入模块时遇到问题,请参阅我在 中的回答。