I know that tools like rollup, webpack and even babel are capable of producing tree-shaken bundles. But I would like to do that, but for an abstract syntax tree I parsed from a file, without writing to disk first. Does that make sense? Is it possible? Thanks in advance!
One of the ways you can achieve what you want is using 🐊Putout code transformer with a couple built-in plugins and one new:
export const fix = (path) => {
path.replaceWith(path.node.declaration);
}
export const include = () => [
'ExportDefaultDeclaration',
'ExportNamedDeclaration'
];
That will remove all kind of exports, since we don't need it in our AST because of tree shake.
It looks this way:
You can edit it in 🐊Putout Editor.
This is the whole tree shaker:
import putout from 'putout';
putout('your code', {
plugins: [
'remove-unused-variables',
'remove-unused-expressions',
'remove-unreachable-code',
'remove-unreferenced-variables',
['remove-export', {
fix: (path) => {
path.replaceWith(path.node.declaration);
},
include: () => [
'ExportDefaultDeclaration',
'ExportNamedDeclaration'
]
}]
]
});
You can take a look to all unsafe transformations from eslint-plugin-putout.
🐊Putout is one of tools I'm working on and I'm always glad to help with any issues related to AST and code transformations.