[Javascript AST] 1. Continue: Write a simple Babel plugin

We want to write a Babel Plugin, which move ‘const versionRegex = /(/d+)\.(/d+)\.(/d+)/gi‘ out of function scope and put it into global scope.

Code:

function getVersion(versionString) {
 const versionRegex = /(\d+)\.(\d+)\.(\d+)/gi
 var x = /foo/.text(‘thing‘)
 const [, major, minor, patch] = versionRegex.exec(versionString)
 return {major, minor, patch}
}

AST:

export default function (babel) {
  const { types: t } = babel;

  return {
    name: "ast-transform", // not required
    visitor: {
      RegExpLiteral(path) {
        // We only want to locate
        // const versionRegex = /(\d+)\.(\d+)\.(\d+)/gi
        // NOT
        // var x = /foo/.text(‘thing‘)
        // for versionRegex, because it is a VariableDeclarator, it has init prop
        // for /foo/, it is under MemeberExpression‘s object prop
        if(path.parentKey !== ‘init‘) {
          return;
        } 

        // Now we locate const versionRegex = /(\d+)\.(\d+)\.(\d+)/gi
        // we want to generate a unqi id for id
        const program = path.find(parent => parent.isProgram())
        const variableDeclarator = path.find(parent => parent.isVariableDeclarator())
        const variableDeclaration = path.find(parent => parent.isVariableDeclaration())
        const {
            node: {
                id: {name: originalName}
            }
        } = variableDeclarator
        const newName = program.scope.generateUidIdentifier(originalName)
        console.log(variableDeclaration)
        // rename the versionRegex
        path.scope.rename(newName.name, originalName)

        // move the regex out of function scope
        // create new versionRegex variable out of function scope
        // and assign the value to it
        const newVariableDeclaration = t.variableDeclaration(variableDeclaration.node.kind, [
            t.variableDeclarator(newName, path.node)
        ])
        program.node.body.unshift(newVariableDeclaration)
        // last remove the old one
        variableDeclarator.remove()

      }
    }
  };
}
时间: 2024-11-10 10:33:51

[Javascript AST] 1. Continue: Write a simple Babel plugin的相关文章

[Javascript AST] 0. Introduction: Write a simple BabelJS plugin

To write a simple Babel plugin, we can use http://astexplorer.net/ to help us. The plugin we want to write is: var foo = 'o' var bar = 'o' foo === bar function foo(foo, bar) { foo === bar; } We want to trasnform the code which highlighted in foo() fu

[AST Babel] Create a simple babel plugin

For example, we have the source code: getVersison('3.4.5') function getVersion(versionString) { const versionRegex = /(\d)\.(\d)\.(\d+)/ const [, major, minor, patch] = versionRegex.exec(versionString) return {major, minor, patch} } We want to transf

[Javascript AST] 4. Continue: Report ESLint error

const disallowedMethods = ["log", "info", "warn", "error", "dir"]; module.exports = { meta: { docs: { description: "Disallow use of console", category: "Best Practices", recommended: tr

An internal error occurred during: "Requesting JavaScript AST from selection". GC overhead limit exc

1.错误描述 An internal error occurred during: "Requesting JavaScript AST from selection". GC overhead limit exceeded 单击"OK"后,提示如下图所示: 2.错误原因 由于用Eclipse编写JavaScript时,出现了return,位置不对,导致错误 3.解决办法 Windows--->Preference--->JavaScript (1)图一

Eclipse--解决eclipse下的Requesting JavaScript AST from selection

解决eclipse下编辑js的报错提示 Requesting JavaScript AST from selection 解决办法: eclipse设置 Window-->Preferences->Javascript-->Editor-->Mark Occurrences 然后取消选中 'Mark occurrences of the selected element in the current file'

从AST编译解析谈到写babel插件

之前一直在掘金上看到一些关于面试写babel插件的文章,最近也在学,以下就是学习后的总结. 关键词:AST编译解析, babel AST编译解析 AST[维基百科]:在计算机科学中,抽象语法树(Abstract Syntax Tree,AST),或简称语法树(Syntax tree),是源代码语法结构的一种抽象表示.它以树状的形式表现编程语言的语法结构,树上的每个节点都表示源代码中的一种结构.之所以说语法是"抽象"的,是因为这里的语法并不会表示出真实语法中出现的每个细节.比如,嵌套括号

ActiveMQ(5.10.0) - Configuring the simple authentication plug-in

The easiest way to secure the broker is through the use of authentication credentials placed directly in the broker’s XML configuration file. Such functionality is provided by the simple authentication plug-in that’s part of ActiveMQ. The following l

[Javascript AST] 2. Write a simple ESLint rule

What we want to do is checking if user write nested if statements which actually can combine to one: // BAD if (a) { console.log("a"); } else { if (b) { console.log("b"); } } // GOOD if (a) { console.log("a"); } else if (b) {

对比JavaScript中的Continue和Break

译者按: 最好是不用,不过基础知识要掌握. 原文: JavaScript: Continue vs Break - Learn the difference between the continue and break statements. 译者: Fundebug 为了保证可读性,本文采用意译而非直译.另外,本文版权归原作者所有,翻译仅用于学习. 在这篇文章中,我们会详细介绍continue和break,分析它们的相同和不同之处,甚至用一些可运行的实例. continue和break都是用于