Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add presets to the tree-shaking options #4131

Merged
merged 7 commits into from Jun 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 28 additions & 2 deletions docs/999-big-list-of-options.md
Expand Up @@ -1379,11 +1379,21 @@ Default: `false`
If this option is provided, bundling will not fail if bindings are imported from a file that does not define these bindings. Instead, new variables will be created for these bindings with the value `undefined`.

#### treeshake
Type: `boolean | { annotations?: boolean, moduleSideEffects?: ModuleSideEffectsOption, propertyReadSideEffects?: boolean | 'always', tryCatchDeoptimization?: boolean, unknownGlobalSideEffects?: boolean }`<br>
Type: `boolean | "smallest" | "safest" | "recommended" | { annotations?: boolean, moduleSideEffects?: ModuleSideEffectsOption, preset?: "smallest" | "safest" | "recommended", propertyReadSideEffects?: boolean | 'always', tryCatchDeoptimization?: boolean, unknownGlobalSideEffects?: boolean }`<br>
CLI: `--treeshake`/`--no-treeshake`<br>
Default: `true`

Whether to apply tree-shaking and to fine-tune the tree-shaking process. Setting this option to `false` will produce bigger bundles but may improve build performance. If you discover a bug caused by the tree-shaking algorithm, please file an issue!
Whether to apply tree-shaking and to fine-tune the tree-shaking process. Setting this option to `false` will produce bigger bundles but may improve build performance. You may also choose one of three presets that will automatically be updated if new options are added:

* `"smallest"` will choose option values for you to minimize output size as much as possible. This should work for most code bases as long as you do not rely on certain patterns, which are currently:
* getters with side effects will only be retained if the return value is used (`treeshake.propertyReadSideEffects: false`)
* code from imported modules will only be retained if at least one exported value is used (`treeshake.moduleSideEffects: false`)
* you should not bundle polyfills that rely on detecting broken builtins (`treeshake.tryCatchDeoptimization: false`)
* some semantic errors may be swallowed (`treeshake.unknownGlobalSideEffects: false`)
* `"recommended"` should work well for most usage patterns. Some semantic errors may be swallowed, though (`treeshake.unknownGlobalSideEffects: false`)
* `"safest"` tries to be as spec compliant as possible while still providing some basic tree-shaking capabilities. This is currently equivalent to `true` but this may change in the next major version.

If you discover a bug caused by the tree-shaking algorithm, please file an issue!
Setting this option to an object implies tree-shaking is enabled and grants the following additional options:

**treeshake.annotations**<br>
Expand Down Expand Up @@ -1492,6 +1502,22 @@ console.log(foo);

Note that despite the name, this option does not "add" side effects to modules that do not have side effects. If it is important that e.g. an empty module is "included" in the bundle because you need this for dependency tracking, the plugin interface allows you to designate modules as being excluded from tree-shaking via the [`resolveId`](guide/en/#resolveid), [`load`](guide/en/#load) or [`transform`](guide/en/#transform) hook.

**treeshake.preset**<br>
Type: `"smallest" | "safest" | "recommended"`<br>
CLI: `--treeshake <value>`<br>

Allows choosing one of the presets listed above while overriding some of the options.

```js
export default {
treeshake: {
preset: 'smallest',
propertyReadSideEffects: true
}
// ...
}
```

**treeshake.propertyReadSideEffects**<br>
Type: `boolean | 'always'`<br>
CLI: `--treeshake.propertyReadSideEffects`/`--no-treeshake.propertyReadSideEffects`<br>
Expand Down
2 changes: 1 addition & 1 deletion src/rollup/rollup.ts
Expand Up @@ -219,7 +219,7 @@ function getOutputOptions(
setAssetSource: emitError
};
}
) as GenericConfigObject,
),
inputOptions,
unsetInputOptions
);
Expand Down
5 changes: 4 additions & 1 deletion src/rollup/types.d.ts
Expand Up @@ -474,9 +474,12 @@ export interface OutputPlugin extends Partial<OutputPluginHooks>, Partial<Output
name: string;
}

type TreeshakingPreset = 'smallest' | 'safest' | 'recommended';

export interface TreeshakingOptions {
annotations?: boolean;
moduleSideEffects?: ModuleSideEffectsOption;
preset?: TreeshakingPreset;
propertyReadSideEffects?: boolean | 'always';
/** @deprecated Use `moduleSideEffects` instead */
pureExternalModules?: PureModulesOption;
Expand Down Expand Up @@ -541,7 +544,7 @@ export interface InputOptions {
preserveSymlinks?: boolean;
shimMissingExports?: boolean;
strictDeprecations?: boolean;
treeshake?: boolean | TreeshakingOptions;
treeshake?: boolean | TreeshakingPreset | TreeshakingOptions;
watch?: WatcherOptions | false;
}

Expand Down
51 changes: 40 additions & 11 deletions src/utils/options/mergeOptions.ts
Expand Up @@ -4,12 +4,20 @@ import {
MergedRollupOptions,
OutputOptions,
RollupCache,
TreeshakingPreset,
WarningHandler,
WarningHandlerWithDefault
} from '../../rollup/types';
import { ensureArray } from '../ensureArray';
import { errInvalidOption, error } from '../error';
import { printQuotedStringList } from '../printStringList';
import { CommandConfigObject } from './normalizeInputOptions';
import { defaultOnWarn, GenericConfigObject, warnUnknownOptions } from './options';
import {
defaultOnWarn,
GenericConfigObject,
treeshakePresets,
warnUnknownOptions
} from './options';

export const commandAliases: { [key: string]: string } = {
c: 'config',
Expand Down Expand Up @@ -121,7 +129,7 @@ function mergeInputOptions(
preserveSymlinks: getOption('preserveSymlinks'),
shimMissingExports: getOption('shimMissingExports'),
strictDeprecations: getOption('strictDeprecations'),
treeshake: getObjectOption(config, overrides, 'treeshake'),
treeshake: getObjectOption(config, overrides, 'treeshake', objectifyTreeshakeOption),
watch: getWatch(config, overrides, 'watch')
};

Expand Down Expand Up @@ -157,32 +165,53 @@ const getOnWarn = (
const getObjectOption = (
config: GenericConfigObject,
overrides: GenericConfigObject,
name: string
name: string,
objectifyValue: (value: unknown) => Record<string, unknown> | undefined = value =>
(typeof value === 'object' ? value : {}) as Record<string, unknown> | undefined
) => {
const commandOption = normalizeObjectOptionValue(overrides[name]);
const configOption = normalizeObjectOptionValue(config[name]);
const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
if (commandOption !== undefined) {
return commandOption && { ...configOption, ...commandOption };
}
return configOption;
};

const objectifyTreeshakeOption = (value: unknown): Record<string, unknown> => {
if (typeof value === 'string') {
const preset = treeshakePresets[value as TreeshakingPreset];
if (preset) {
return preset as unknown as Record<string, unknown>;
}
error(
errInvalidOption(
'treeshake',
`valid values are false, true, ${printQuotedStringList(
Object.keys(treeshakePresets)
)}. You can also supply an object for more fine-grained control`
)
);
}
return typeof value === 'object' ? (value as Record<string, unknown>) : {};
};

const getWatch = (config: GenericConfigObject, overrides: GenericConfigObject, name: string) =>
config.watch !== false && getObjectOption(config, overrides, name);

export const normalizeObjectOptionValue = (
optionValue: unknown
optionValue: unknown,
objectifyValue: (value: unknown) => Record<string, unknown> | undefined
): Record<string, unknown> | undefined => {
if (!optionValue) {
return optionValue as undefined;
}
if (Array.isArray(optionValue)) {
return optionValue.reduce((result, value) => value && result && { ...result, ...value }, {});
}
if (typeof optionValue !== 'object') {
return {};
return optionValue.reduce(
(result, value) => value && result && { ...result, ...objectifyValue(value) },
{}
);
}
return optionValue as Record<string, unknown>;
return objectifyValue(optionValue);
};

type CompleteOutputOptions<U extends keyof OutputOptions> = {
Expand Down