Babel plugin demo

index.js
复制

const babel = require('babel-core')

const code = `
const abc = 1 + 2 // foo
const defghijk = 3 + 4 // bar
`

const result = babel.transform(code, {
    plugins: [require('./plugin')]
})

console.log(result.code)

plugin.js
复制

// var babel = require('babel-core')
// var t = require('babel-types')

/**
 *
 * @param { import('babel-core') } babel
 * @returns
 */
function myPlugin(babel) {
    const { types: t } = babel

    /**
     * @typedef { Object } BabelPlugin
     * @property { import('babel-traverse').Visitor } visitor
     */

    /** @type {BabelPlugin}  */
    const plugin = {
        visitor: {
            VariableDeclaration(path) {
                // path.node.id.name = path.node.id.name + '    '
                const nextPaths = []

                let prevPath = path

                while (true) {
                    const next = path.getNextSibling()

                    if (!next || !next.node) {
                        break
                    }

                    if (prevPath.node.loc.start.line + 1 === next.node.loc.start.line) {
                        nextPaths.push(next)
                        prevPath = next
                    } else {
                        break
                    }
                }

                console.log(nextPaths)
            }
        }
    }

    return plugin
}

module.exports = myPlugin

大牛们的评论:朕有话说

还没有人评论哦,赶紧抢沙发!