Reputation: 99
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
Upvotes: 9
Views: 24452
Reputation: 31
I imported the format function with aliasing and it solved the issue.
import { format as format_date } from 'date-fns'
Upvotes: 0
Reputation: 31
I have managed to fix it by adding "esModuleInterop": true to tsconfig.json.
Upvotes: 3
Reputation: 3185
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.
Upvotes: 1