2

I installed date-fns as per the following instruction on https://www.npmjs.com/package/date-fns

npm install date-fns --save

After that my package.json is updated with the following entry:

{
  "dependencies": {
    "date-fns": "^2.23.0"
  }
}

Then, I wrote the following code from https://date-fns.org/ and it resulted in error:

import { format, formatDistance, formatRelative, subDays } from 'date-fns'

format(new Date(), "'Today is a' eeee")

Error:

import { format, formatDistance, formatRelative, subDays } from 'date-fns'
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:703:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at Function.Module._load (internal/modules/cjs/loader.js:555:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:822:10)
    at internal/main/run_main_module.js:17:11

[Done] exited with code=1 in 0.143 seconds

node -v:

v12.2.0

enter image description here

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110

2 Answers2

3

I managed to run it successfully by using require as shown below:

const fns = require('date-fns')

console.log(fns.format(new Date(), "'Today is a' eeee"))

Update:

I installed node v16.6.1 following the instructions in this answer and now I can run the following code successfully:

import { format } from 'date-fns';

console.log(format(new Date(), "yyyy-MM-dd'T'HH:mm:ss.SSS"));
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

You are probably facing syntax errors, as you directly copy pasted the code from the documentation. Try importing the library as follows. It should work just fine.

import { format, formatDistance, formatRelative, subDays } from 'date-fns';

const mDate= format(new Date(2014, 1, 11), 'MM/dd/yyyy');
console.log(mDate);
Salvino D'sa
  • 4,018
  • 1
  • 7
  • 19
  • I am quite sure it does require semicolons at least for the import statements. Can you try the code in my answer? – Salvino D'sa Aug 03 '21 at 17:42
  • Salvino - I did try your code but the error persists. – Arvind Kumar Avinash Aug 03 '21 at 17:47
  • Can you delete the `node_modules` folder and try running `npm install` and see if that works? Because the node js version you are running is quite sufficient for running date-fns without any issues. I have used date-fns tones of times and didn't face any issues with the above code. – Salvino D'sa Aug 03 '21 at 17:48
  • Salvino - I deleted `node_modules` folder and executed `npm install date-fns --save` which recreated this folder but the problem remains as it is. I am quite new to node-js and probably missing some basic step. – Arvind Kumar Avinash Aug 03 '21 at 17:55