1

In ES6, I know that you can import named exports like:

import { foo } from 'bar'

Which is useful in certain module bundlers like Webpack so that it is aware of exactly what is being used in any context. I'd like to be able to do this but keep them name-spaced. I've tried:

import { foo } as bar from 'bar' // syntax error

But that doesn't work. I know I could do something like this:

import * as bar from 'bar'

To get all 'bar's exports in a namespace, but my understanding is that it's best practice to only import what you need so that a module bundler can shake the tree effectively.

I only want to do this for readability, so when skimming code I know what module I'm running functions from. I know that I could do this for nearly the same effect:

import { foo as bar_foo } from 'bar'
console.log(bar_foo)

Or moving the same idea into file 'bar':

// bar.js
const bar = { foo }
export bar_foo = bar.foo
export default bar

// other.js
import bar_foo from 'bar'

Which is similar but handles the name change. It seems pretty okay as long as you know what it's signifying.

If this is impossible but there's a better or accepted convention to deal with the issue that would also be a good answer.

EDIT: @loganfsmyth informed me that ES6 loads the whole file regardless. I realized that this practice would only have any value within module bundlers like Webpack that remove any unused code. I have edited this post to specify that I'm referring to using this pattern within Webpack or a similar module bundler.

Matt O'Tousa
  • 515
  • 2
  • 11
  • No, `import * as bar from 'bar'` is not a bad practice. – Jonas Wilms Apr 19 '18 at 19:37
  • Whether you list the imports or use `* as bar`, either way you're loading that whole file and everything in it. – loganfsmyth Apr 19 '18 at 19:40
  • what is bad with `import { foo as bar } from 'bar'`? – madox2 Apr 19 '18 at 19:47
  • @loganfsmyth I didn't realize that. I guess my question is referring to build tools and not ES6 in general then. Webpack 'shakes the tree' and removes anything that's unused so there is an advantage to named imports. I do also think that there is some value to seeing exactly what you will be using right at the top of the file. – Matt O'Tousa Apr 19 '18 at 19:58
  • Webpack is able to handle both FYI: https://stackoverflow.com/questions/45735534/is-using-an-es6-import-to-load-specific-names-faster-than-importing-a-namespace As for readability, definitely in the eye of the beholder there. – loganfsmyth Apr 19 '18 at 20:03
  • @loganfsmyth Ah, I underestimated Webpack then. If you want to say as much in an answer I'll accept it, or maybe it's better to mark this as a duplicate? – Matt O'Tousa Apr 19 '18 at 20:14

0 Answers0