0

I'm using import { isValid, format, parse, subHours, differenceInHours } from 'date-fns'; in one of the .js file.

In test, I imported the file correctly and tests passed, but when starting server I see issue -

[error] - Error initializing server ../utils.js
(function (exports, require, module, __filename, __dirname) { import { isValid, format, parse, subHours, differenceInHours } from 'date-fns';

SyntaxError: Unexpected token import
at createScript (vm.js:74:10)

Do you see any mistake in way I should import?

Prakhar
  • 1,096
  • 1
  • 16
  • 41
  • This answer may help: https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node – sbolel Jan 23 '19 at 07:25

2 Answers2

0

SyntaxError: Unexpected token import is usually because the version of javascript/node that is running the code isn't new enough; it doesn't know about the keyword import.

Instead of import { isValid, format, parse, subHours, differenceInHours } from 'date-fns'; try using the require() method...

This should work for node 6.4.0 and above:

const { isValid, format, parse, subHours, differenceInHours } = require('date-fns');

or something like this for node 4

var dateFns = require('date-fns');

var isValidDate = dateFns.isValid;
var formatDate = dateFns.format;
Ryan953
  • 680
  • 5
  • 11
0

You imported it right. a possible problem could be you are trying to use it without installing the package(date-fns) on your project. just check it's existance in your project's package.json. if you couldn't find it, install using npm

npm i date-fns