Optimizing JavaScript packages for tree shaking

Geoffrey Dhuyvetters from madewithlove on how authors of (open source) JavaScript packages can optimize their builds for tree shaking:

How do we create a package that exposes both CommonJS & ES modules while making sure we don’t break cross-platform support? Publishing 2 separate packages is an option (e.g. lodash/lodash-es). But there is a nicer, more maintainable option that obviates the need to publish twice. We can provide an extra build step that creates an ES version of our package and links it via package.json.

The package.json links both builds like so:

  "main": "build/cjs/index.js",
  "module": "build/esm/index.js",

Didn’t know you could als provide a module field, similar to name … handy!

Optimizing JavaScript packages for tree shaking →

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.