0

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!

Soska
  • 699
  • 7
  • 11
  • Wouldn't that involve solving the halting problem as prerequisite? You want to parse random code and remove dead statements from it. There are tools that find dead code (e.g., ESLint does it) but I'm not sure it can be applied generally. E.g., if the entire code is the statement `x = 1`, is that dead code? It would cause a side-effect, so removing it *might* change how the program behaves. Unless you have any sort of guarantee of the completeness of the code, I'm not sure this problem is really solvable. – VLAZ Feb 07 '22 at 17:30
  • All these tools do not just have a cli working on the file system, but also a js api working with arbitrary data (strings or ast). Look into their documentation. – Bergi Feb 07 '22 at 18:09
  • @VLAZ I don't think that's what the OP is asking for – Bergi Feb 07 '22 at 18:10

1 Answers1

0

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:

treeshake using Putout

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.

coderaiser
  • 749
  • 5
  • 15
  • 1
    [Please add a disclosure that you are affiliated with putout](https://stackoverflow.com/help/promotion). – VLAZ Feb 15 '22 at 19:50