7

I need to understand when I use a named import like this

import { render } from 'react-dom'

does webpack include in the bundle only the render method or the whole module especially when using tree shaking by setting module to false in babel configuration and let webpack take care about them?

Also in the case of importing react

import React from 'react'

&&

import React, { Component, PropTypes } from 'react'

what's the right way?

4
  • I'm not sure about the first question, but the second question: importing React like that is pretty common, especially the second statement, because you don't want to type React.Component and React.PropTypes every time. So they're both OK. If you are using class based components and defining the prop types, you can use the second statement. The destructuring is for your convenience.
    – nbkhope
    Commented Mar 31, 2017 at 17:07
  • But that does not require more memory because we are declaring 3 variables instead of one? Commented Mar 31, 2017 at 17:08
  • Why don't you see what Babel transpiles here: babeljs.io/repl/…
    – nbkhope
    Commented Mar 31, 2017 at 17:10
  • @nbkhope I am here talking about the case when webpack is tacking care about modules not babel Commented Mar 31, 2017 at 17:18

1 Answer 1

5

Tree-Shaking is applicable for modules which can be statically analysed (to get the entire dependency tree without running the code) - and it is ONLY for ES2015 Modules and NOT CommonJS(node) modules.

react, react-dom, as of this writing ([email protected]), are NOT published as ES2015 modules. So either of these -

import { render } from "react-dom";

or

import ReactDOM from "react-dom";

will result in the entire react-dom being included in your bundle. The same applies for react and other libraries which are published as CommonJS modules or UMD.

2
  • So as I understand for third-party code until now we can't benefit from tree shaking, and for own modules that are written as ES2015 modules is applicable? Commented Apr 2, 2017 at 15:00
  • @ziedhajsalah yes. Commented Apr 3, 2017 at 19:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.