7

I have a project in which I bundle a components library using Rollup (generating a bundle.esm.js file). These components are then used in another project, that generates web pages which use these components - each page is using different components. The problem is, that the entire components library is always bundled with the different page bundles, regardless of which components I'm using, unnecessarily increasing the bundle size.

This is my Rollup setup:

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import pkg from './package.json';

const extensions = [
  '.js', '.jsx', '.ts', '.tsx',
];
export default [
  {
    input: './src/base/index.ts',
    plugins: [
      peerDepsExternal(),
      resolve({ extensions }),
      babel({
        exclude: 'node_modules/**',
        extensions,
      }),
      commonjs(),
    ],
    output: [
      { file: pkg.main, format: 'cjs', sourcemap: true },
      { file: pkg.module, format: 'es', sourcemap: true },
    ],
    watch: {
      clearScreen: false,
    },
  },
];

I have "modules" set to false in webpack, as well.

4

1 回答 1

8

您需要做一些事情来从双方实现可摇动的代码 - 构建的包和使用它的项目。

从您的代码片段中,我看到您没有preserveModules: true在汇总配置文件中添加标志以防止构建输出捆绑。Webpack 不能对捆绑的文件进行 treeshake仅供参考

export default {
  ...
  preserveModules: true,
  ...
}

在使用它的项目方面,您必须sideEffectspackage.json- 阅读文档中指定以了解如何配置它们。除此之外,optimization在 webpack 中必须有sideEffects: true,还请阅读此处的文档。

希望这可以帮助!

于 2020-06-27T07:15:32.730 回答