为什么 Rollup.js 不对我的库进行 treeshake

Why doesn't Rollup.js treeshake my library

我有一个实用程序库:goodcore 我正在另一个项目中使用。它工作正常,但是当我使用 Rollup 对其进行捆绑和 treeshake 时,它​​始终包含整个 goodcore 库,即使我只使用其中的很小一部分,但与某些包含的文件没有任何链接.

两个项目都是Typescript,使用ES2015模块加载。

我引用 goodcore 库使用:

import { Arr, Pool, Range2, Timer, Util, Vec2 } from "goodcore";

goodcore 中的 index.js 看起来像:

export { Vec2 as Vec2 } from "./struct/Vec2";
export { Range2 as Range2 } from "./struct/Range2";
export { Rect as Rect } from "./struct/Rect";
export { List as List } from "./struct/List";
export { Dictionary as Dictionary } from "./struct/Dictionary";
export { Stack as Stack } from "./struct/Stack";
export { Tree as Tree } from "./struct/Tree";
export { Calc as Calc } from "./Calc";
export { Dom as Dom } from "./Dom";
export { Arr as Arr } from "./Arr";
export { Obj as Obj } from "./Obj";
export { Util as Util } from "./Util";
export { Timer as Timer } from "./Timer";
export { Uri as Uri } from "./Uri";
export { Poolable as Poolable } from "./standard/mixins/Poolable";
export { Initable as Initable } from "./standard/mixins/Initable";
export { Pool as Pool } from "./standard/Pool";
export { Integrate as Integrate } from "./Integration";
export { MocData as MocData } from "./MocData";
export { Cache as Cache } from "./standard/Cache";
export { KeyValuePair as KeyValuePair } from "./struct/KeyValuePair";
//# sourceMappingURL=index.js.map

我最终还是得到了来自 goodcore 的所有东西,比如树,包含在我对另一个项目的汇总构建中,而我的印象是摇树应该删除不是 used/referenced 的东西。

另一个项目的汇总配置如下所示:

var packageJson = require("./package.json");
import resolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
export default {
    entry: 'src/lib/index.ts',
    targets: [
            { dest: 'dist/' + packageJson.name + '.umd.js', format: 'umd' },
            { dest: 'dist/' + packageJson.name + '.es.js', format: 'es' },
            { dest: 'dist/' + packageJson.name + '.iife.js', format: 'iife' }
    ],
    moduleName: packageJson.name,
    external: ['ts-md5/dist/md5'],
    sourceMap: true,
    globals: {
    },
    treeshake: true,
    plugins: [
        typescript({
            typescript: require('typescript')
        }),
        resolve({ module: true, jsnext: false, main: true, modulesOnly: true })
    ]
}

我做错了什么?

为了确保正确性,Rollup 将包括任何看起来可能有副作用的代码——举一个简单的例子,这个包会导致 'hello from foo.js' 被记录,即使 foo 没有'由 main.js 导入:

/*--- main.js ---*/
import './foo.js';

/*--- foo.js  ---*/
export function unused () {
  // this will be omitted...
}

// but this will be included, because it has an effect on the world
console.log('hello from foo.js');

在 goodcore 的情况下,一切 看起来 Rollup 好像它可能有副作用。例如,Calc是调用_Calc()的结果,由于很难判断_Calc()是否有效果,所以无论[=13=是否有效,都必须包含它] 被捆绑使用。你可以 see this in the REPL.

不幸的是,使此代码可摇动树可能需要对设计进行相当大的更改。 TypeScript 也有可能引入了不可摇动的结构。