Creating an NPM package that enables ES6 imports to cherry pick exports

995 views Asked by At

When building an NPM package, how do you create a build that is able to support cherry picking individual exports to save on Webpack, Rollup or Browserify bundle size?

Preferred syntax would be:

import { myModuleOne, myModuleTwo } from 'my-npm-package';

Or

import myModuleOne from 'my-npm-package/myModuleOne';
import myModuleTwo from 'my-npm-package/myModuleTwo';
1

There are 1 answers

1
Michał Perłakowski On BEST ANSWER

Just use ES6 exports:

export const myModuleOne = ...
export const myModuleTwo = ...

And in package.json set the module property to the path of your bundle:

{
  main: 'path/to/umd/bundle.js',
  module: 'path/to/es/bundle.js',
  ...
}

Rollup and webpack 2 have tree-shaking, so the generated bundle will include only the modules you need.