0

Let's say I have a JavaScript file with an array of literals:

[
    "foo",
    [
        "bar",
        123
    ],
    "baz"
]

How could I rewrite that file by parsing and manipulating the AST (not process the values at runtime) to flatten the array, resulting in:

["foo", "bar", 123, "baz"]

I know I can get an ESTree from Acorn, for example, but have no idea how to proceed from there:

const code = fs.readFileSync(file, 'utf8')
const ast = acorn.parse(code)
const newCode = ast.???
fs.writeFileSync(file, newCode)
AnC
  • 4,099
  • 8
  • 43
  • 69
  • Parse it as JSON and then use `Array.prototype.flat()`. – Pointy Sep 07 '19 at 15:08
  • I'm not talking about runtime processing, but AST manipulation in a compile step beforehand (thus "rewrite that file"). I've only excerpted the relevant part of that file here, there's JavaScript code surrounding the array, so parsing it as JSON won't work. That's also why this isn't a duplicate, @jack-bashford. – AnC Sep 07 '19 at 15:17

0 Answers0