title: How can I export multiple React components in reusable NPM package so they can be imported independently & exclude dependencies from app bundles?
body: <p>Can I make an NPM package containing multiple React Components that can be independently imported in consuming apps?</p>
  
  <p>I have a NPM package with two reusable React components. The one component imports a heavy/sizeable 3rd party library. The other component does not import this 3rd party library.</p>
  
  <p>I would like to be able to use these components in consuming apps and only include the heavy 3rd party library in my app bundles if I have imported the reusable component that imports the heavy library.</p>
  
  <p>Is there a way to setup my reusable package that will not include the 'heavy-library' in my app bundle if I do not use the HeavyWeight component?</p>
  
  <pre class="lang-js prettyprint-override"><code>// My NPM package
  // components/HeavyWeight.js
  import React from 'react';
  
  import heavyLibrary from 'heavy-library'; // This component imports a very heavy library
  
  const HeavyWeight = () =&gt; {
    const a = heavyFunction();
    return (
      &lt;div&gt;
        {a}
      &lt;/div&gt;
    );
  }
  
  export default HeavyWeight;
  
  
  // components/LightWeight.js 
  import React from 'react';
  
  const LightWeight = () =&gt; {
    return (
      &lt;div&gt;
        I'm light weight.
      &lt;/div&gt;
    );
  }
  
  export default LightWeight;
  
  
  // index.js
  import HeavyWeight from './components/HeavyWeight';
  import LightWeight from './components/LightWeight';
  
  export { HeavyWeight, LightWeight};
  
  // webpack.config.js
  // ...
  module.exports = {
    //...
    externals: {
      heavy-library: 'heavy-library'
    }
  };
  
  
  // Two of my apps using my reusable components
  // appA.js
  // Bundling this app should include 'heavy-library' in final webpack bundle
  import { HeavyWeight } from 'reusable-package';
  
  // appB.js
  // Bundling this app should not include 'heavy-library' in final webpack bundle
  import { LIghtWeight } from 'reusable-package';
  </code></pre>