3

Can I make an NPM package containing multiple React Components that can be independently imported in consuming apps?

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.

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.

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?

// My NPM package
// components/HeavyWeight.js
import React from 'react';

import heavyLibrary from 'heavy-library'; // This component imports a very heavy library

const HeavyWeight = () => {
  const a = heavyFunction();
  return (
    <div>
      {a}
    </div>
  );
}

export default HeavyWeight;


// components/LightWeight.js 
import React from 'react';

const LightWeight = () => {
  return (
    <div>
      I'm light weight.
    </div>
  );
}

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';
sizeight
  • 719
  • 1
  • 8
  • 19
  • This can be done via webpack. You can export multiple outputs for your library and then the consumer can import the specific minified js they want to use, – Mohit Oct 29 '19 at 13:13
  • Could you point me in the right direction to achieve this? – sizeight Oct 29 '19 at 13:15
  • https://stackoverflow.com/questions/35903246/how-to-create-multiple-output-paths-in-webpack-config I guess this is what you all need. – Mohit Oct 29 '19 at 13:22
  • In my package.json I specify "main": "lib/heavy-library.min.js", then I can import from 'heavy-library'. How would I specify the new output in the package.json so that I can also import it? – sizeight Oct 29 '19 at 13:34
  • Could you please provide the snippet for your package.json file? – Mohit Oct 29 '19 at 13:44
  • Think I got it... The default heavy lib would be imported like `import { HeavyWeight } from 'my-lib'` and the alternative light weight version like this `import { LightWeight } from 'mylib/lib/light-library'` – sizeight Oct 29 '19 at 13:52
  • Does it resolves your issue? – Mohit Oct 29 '19 at 14:05

0 Answers0