Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

抽象语法树例子 #38

Open
msforest opened this issue Dec 29, 2020 · 0 comments
Open

抽象语法树例子 #38

msforest opened this issue Dec 29, 2020 · 0 comments

Comments

@msforest
Copy link
Owner

var esprima = require('esprima')
var estraverse = require('estraverse')
var escodegen = require('escodegen')

var fs = require('fs')
var path = require('path')

// 保留注释
function update(filename) {
  var code = fs.readFileSync(filename, 'utf8')
  var ast = esprima.parseModule(code, {
    tokens: true,
    comment: true,
    range: true,
  })
  ast = escodegen.attachComments(ast, ast.comments, ast.tokens)
  estraverse.traverse(ast, {
    enter(node) {
      if (node.type === 'ImportDeclaration') {
        node.source.value = ''
      }
    }
  })
  var newCode = escodegen.generate(ast, {
    format: {
      indent: {
        adjustMulfilineComment: true
      }
    },
    comment: true
  })

  fs.writeFileSync(filename, newCode)
}

function travel(dir) {
  if (fs.statSync(dir).isFile()) {
    return update(dir)
  }

  var dirs = fs.readdirSync(dir)
  dirs.forEach((file) => {
    var pathname = path.join(dir, file)
    if(fs.statSync(pathname).isDirector()) {
      travel(pathname)
    } else {
      update(pathname)
    }
  })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant