Skip to content

Instantly share code, notes, and snippets.

@philholden
Last active April 25, 2016 16:13
Show Gist options
  • Save philholden/25618771eed1e0fd58437f7af2fb8005 to your computer and use it in GitHub Desktop.
Save philholden/25618771eed1e0fd58437f7af2fb8005 to your computer and use it in GitHub Desktop.

Selective import as object proposal

Currently imports can be namespaced using import * as:

import * as foo from './fooCrud'
import * as bar from './barCrud'

// bundles:
// 8 functions
// create, read, update & delete x 2

const id1 = foo.create('hello')
const id2 = bar.create('world')

foo.update(id1, 'hello')
bar.update(id2, 'world')

Currently selective imports can be used to aid tree shaking at build time (with Webpack 2, Rollup etc):

import {
  create as fooCreate,
  update as fooUpdate
} from './fooCrud'

import {
  create as barCreate,
  update as barUpdate
} from './barCrud'

// bundles:
// only 4 functions
// fooCreate, fooUpdate, barCreate, barUpdate
//
// but need to rename each function explicitly
// to avoid namespace collision

const id1 = fooCreate('hello')
const id2 = barCreate('world')

fooUpdate(id1, 'hello')
barUpdate(id2, 'world')

It would be nice to not have to choose between namespacing and tree shaking as both are desirable:

import { create, update } as foo from './fooCrud'
import { create, update } as bar from './barCrud'

// bundles:
// only 4 functions
// create, update x 2
// no rename needed

const id1 = foo.create('hello')
const id2 = bar.create('world')

foo.update(id1, 'hello')
bar.update(id2, 'world')

Naming things is hard. With proper namespacing we can reuse common short function and constant names in our exports giving a very predictable module interface. We do not need to repeat the module name in functions and remember if it is fooCreate or createFoo.

Treeshaking is very desirable for producing small script downloads for mobile devices.

A symmetrical API would imply we also provide:

export { create, update, delete } as mutations
@caridy
Copy link

caridy commented Apr 25, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment