简体   繁体   中英

TypeError: format is not a function in date-fns

I am migrating from moment to date-fns and following docs on the official site.

I have installed date-fns from npm and when I try to use I get this error:

TypeError: format is not a function

I have tried import, require but they all give same error.

var format = require('date-fns/format')
import format from 'date-fns/format'

Also the typeof(format) returns undefined .

Using v1.29.0 on Nodejs

从文档。

import { format } from 'date-fns';

I followed the same step as you did and it works fine for me.

Most Important: Upgrade your node version to v8.X or above.I am using node v10.8.0. You can follow here to upgrade version.

The library is available as an npm package, a Bower package, and is also distributed through a CDN.

You can use this properly by following give steps:

Step 1: First, you can install the package via running following command. (You might forget to install the package)

npm install date-fns --save

or

yarn add date-fns .   

Step 2: It is used to get the formatted date string in the various formats and if you are using ES15 standards then you can import the package by adding following line above to your code.

import format from 'date-fns/format'

Step 3: Syntax for use will be as follow and list of various formats are given in the official doc. you can take reference from here

format(date, [format='YYYY-MM-DDTHH:mm:ss.SSSZ', [options]])

Step 4: To take better understanding here is the simple example:

 var result = format(
      new Date(2014, 1, 11),
      'MM/DD/YYYY'
    ) 
console.log('Result: ',result);

Conclusion: I tried all the above steps and I got the following result in console:

Result:  02/11/2014

Alternatively: Try running follow code with REPL.
Step 1: Open your terminal and run the command sudo node

Step 2: Copy and paste below code in your terminal

var format = require('date-fns/format');
var result = format(
    new Date(2014, 1, 11),
    'MM/DD/YYYY'
) 
console.log('Result: ',result);

Step 3: Press enter and you will get Result: 02/11/2014 in your terminal console.

我设法通过向 tsconfig.json 添加 "esModuleInterop": true 来修复它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM