简体   繁体   中英

Create unique identifier in babel plugin

I want to create global variables and be sure that they don't conflict with existing global varibale names.

Example with replacing all array declarations:

let arrayDeclarations

const customPlugin = () => {
  return {
    visitor: {
      Program(path) {
        arrayDeclarations = []
        path.node.body.unshift(t.variableDeclaration('const', arrayDeclarations))
      },
      ArrayExpression(path) {
        const newUniqueName = // TODO
        const arrayIdentifier = t.identifier(newUniqueName)
        arrayDeclarations.push(t.variableDeclarator(arrayIdentifier, path.node))
        path.replaceWith(arrayIdentifier)
      }
    }
  }
}

babel 手册中找到了答案:

const newUniqueName = path.scope.generateUidIdentifier('a')

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