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';