Skip to content

Instantly share code, notes, and snippets.

@nuintun
Created August 25, 2025 01:39
Show Gist options
  • Save nuintun/aa8e52eb07b26c68ed19de48ea3300ee to your computer and use it in GitHub Desktop.
Save nuintun/aa8e52eb07b26c68ed19de48ea3300ee to your computer and use it in GitHub Desktop.
修复旧版 TypeScript 产物无法被 Tree-Shake 的问题
/**
* @module treeShake
*/
import MagicString from 'magic-string';
/***
* @function treeShake
* @description Fixed tree shaking for typescript and rollup preserve modules.
* @return {import('rollup').Plugin}
*/
export default function treeShake() {
return {
name: 'rollup-plugin-tree-shake',
generateBundle(options, bundle) {
const files = Object.entries(bundle);
for (const [, file] of files) {
if (file.type !== 'asset') {
const code = new MagicString(file.code);
this.parse(file.code, {
sourceType: 'module',
onComment(block, text, start, end) {
if (block && text === '* @class ') {
code.overwrite(start, end, '/*#__PURE__*/');
}
}
});
if (options.sourcemap) {
file.map = code.generateMap();
}
file.code = code.toString();
}
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment