babeljsbabel-plugincodemod

Babel plugin addComment doesn't work when ran with codemod


I've created a babel plugin:

    module.exports = function (babel) {
        const { types: t } = babel;
        return {
            name: 'addComment',
            visitor: {
                Program(path, state) {
                    path.addComment('leading', '@@@ My precious @@@');
                    path.unshiftContainer('body', t.noop());
                }
            }
        };
    }

I expect that it should add a comment line // @@@ My precious @@@ to the top of the module and add a blank line after the comment.

I ran this plugin with @codemod/cli:

./node_modules/.bin/codemod --plugin ./babel-plugin.js ./transform-me.js

And I got only a blank line inserted in the source file and no comment line. If I try the same code in the astexplorer.net, it works fine.

I've tried to add .babelrc file with "comments": true option and run codemod with the --find-babel-config param. The same result.

What did I do wrong?


Solution

  • I've found a decision. If I manipulate comments array directly, then comments are inserted:

    function addComment(path, comment) {
        const rootNode = path.node.body[0];
        if (!rootNode.comments) {
          rootNode.comments = [];
        }
    
        rootNode.comments.push({
            leading: true,
            trailing: false,
            value: comment,
            type: 'CommentLine'
        });
    }
    
    path.addComment('leading', 'my comment') -> addComment(path, 'my comment')