简体   繁体   中英

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?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM