ECMAScript Modules in date-fns v2

Oct 4, 2018
2 mins read
Sasha 🐑💨 Koss

In this post, I tell about ECMAScript Modules support in date-fns v2 that among other goodies enables tree-shaking out of the box.

date-fns v2 introduces many new features and breaking changes and this post in a part of the series #date_fns_v2 where we describe in detail most notable ones.

Now a bundler that supports tree-shaking will be able to strip date-fns of unused functionality properly:

import { toDate } from 'date-fns'
console.log(toDate(null).toString() === 'Invalid Date')
//=> true

This code will produce 2kB bundle.

ECMAScript Modules also allows TypeScript developers to use more idiomatic importing:

// Before
import * as format from 'date-fns/format'
// Now
import format from 'date-fns/format'

date-fns contains source code in two variations:

- CommonJS located in the root of the package.

- ECMAScript Modules located in esm submodule.

The date-fns repo contains source code that uses ECMAScript Modules. When we build the package, we use Babel we generate CommonJS functions.

Each function in both variations has package.json next to it with sideEffects set to false. This setting enables a bundler to determine if the module doesn't produce side effects and hence could be tree-shaked.

CommonJS versions of the functions also have module field in the package.json that points to the corresponding function in esm submodules:

{
  "sideEffects": false,
  "module": "../esm/toDate/index.js",
  "typings": "../typings.d.ts"
}
・・・
Happy coding time! Please support us at Open Collective: https://opencollective.com/date-fns