AndrewMcLagan
AndrewMcLagan

Reputation: 13987

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

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';

Upvotes: 3

Views: 1022

Answers (1)

Michał Perłakowski
Michał Perłakowski

Reputation: 92639

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.

Upvotes: 4

Related Questions