Cannot find module 'date-fns'

Try using this instead First import the modules

In the terminal type

npm install date-fns @types/date-fns

Then in code

import * as startOfDay from "date-fns";

Should I say instead

import * as startOfDay from 'date-fns/startOfDay';

Seems I have been doing similar things with other libraries in Angular Typescript code.


If you specifically only want to use the start_of_day function you should instead follow the documentation.

Installation with npm

npm install date-fns --save

or with yarn:

yarn add date-fns

Example usage:

// option 1
var startOfDay = require('date-fns/start_of_day');

// option 2
// import * as startOfDay from 'date-fns/startOfDay';

// option 3 (only 2.0.0-alpha.25 or higher)
// import { startOfDay } from 'date-fns';

// The start of a day for 2 September 2014 11:55:00:
var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0));
//=> Tue Sep 02 2014 00:00:00

Benefits

Options 1 and 2 should allow most build tools to easily only include what you actually use, thus making your final bundle smaller and thus your web app load slightly faster. Webpack 4 and possibly other build tools that look at the sideffect flag added to the library will also be able to treeshake option 3, further given that you're using 2.0.0-alpha.25 or higher.

Date-fns general modularity is currently the main advantage I see "date-fns" have compared to the more popular and established "moment". Though the author also explains other advantages in a github issue.

Don't import all of "date-fns"

Both of the mentioned working solutions simply fetch the entirety of the "date-fns" library and as such is still a valid syntax but labeling the variable as "startOfDay" gives the impression that the only part actually loaded or used is this function. When all of the other functions are also loaded in vain. Where "start_of_day" is just one of many functions loaded on the same object.

So if you really want to load all of the functions you should instead call the variable "date-fns". However given the ease and benefits I don't see why you wouldn't just follow the documentation and import individual functions.

Type Definitions

EDIT: With TypeScript 2+ you will get the type definitions directly from the library (version 1.23+).

Earlier versions (version 1.22.x and lower) should instead follow Edwin Kato's advice on installing the type definitions for "date-fns". You should however also save it to your local dev-dependencies in "package.json". You will need to explicitly state this when using npm. While with yarn you need to state that it's a dev-dependency and not a regular dependency.

Thus you should install it like this with npm:

npm install @types/date-fns --save-dev

or with yarn:

yarn add @types/date-fns --dev