1

我有一个实用程序库: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 的所有东西,比如 Tree,包含在另一个项目的汇总构建中,而我的印象是 treeshaking 应该删除未使用/引用的东西。

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

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 })
    ]
}

我究竟做错了什么?

4

1 回答 1

2

为了确保正确性,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()有效果,所以无论是否Calc被bundle使用,都必须包含它。您可以在 REPL 中看到这一点

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

于 2017-05-18T00:54:01.637 回答