3

我可以制作一个包含多个可以在消费应用程序中独立导入的 React 组件的 NPM 包吗?

我有一个带有两个可重用 React 组件的 NPM 包。一个组件导入一个沉重/相当大的第 3 方库。其他组件不导入此第 3 方库。

我希望能够在使用应用程序时使用这些组件,并且如果我已导入可重用组件来导入重型库,则仅在我的应用程序包中包含重型 3rd 方库。

如果我不使用 HeavyWeight 组件,有没有办法设置我的可重用包,它不会在我的应用程序包中包含“重库”?

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

0 回答 0