Created
February 11, 2023 13:27
-
-
Save lisonge/51f6a7e6118a3412ecc226d20ea4fa0d to your computer and use it in GitHub Desktop.
replace specified node in json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import MagicString from 'magic-string'; | |
import * as acorn from 'acorn'; | |
const prefix = `const x=`; | |
const code = `${prefix}{ | |
"pages": ["pages/index/index"], | |
"subpackages": [ | |
{ | |
"name": "A", | |
"pages": ["innerModule/pages/index/index"] | |
}, | |
{ | |
"name": "B", | |
"pages": ["innerModule/pages/index/index"] | |
} | |
] | |
}`; | |
const newNode = { | |
name: `A`, | |
pages: [`new/path`], | |
}; | |
const ast: any = acorn.parse(code, { ecmaVersion: 'latest' }); | |
const subpackagesNodes: any[] = | |
ast.body[0].declarations[0].init.properties[1].value.elements; | |
const targetNode = subpackagesNodes.find( | |
(n) => n.properties[0].value.value == 'A', | |
); | |
const ms = new MagicString(code); | |
if (targetNode) { | |
const nameNode = targetNode.properties[0].value; | |
const pagesNode = targetNode.properties[1].value; | |
ms.update(nameNode.start, nameNode.end, JSON.stringify(newNode.name)); | |
ms.update(pagesNode.start, pagesNode.end, JSON.stringify(newNode.pages)); | |
console.log(ms.toString().substring(prefix.length)); | |
} | |
// output | |
// { | |
// "pages": ["pages/index/index"], | |
// "subpackages": [ | |
// { | |
// "name": "A", | |
// "pages": ["new/path"] | |
// }, | |
// { | |
// "name": "B", | |
// "pages": ["innerModule/pages/index/index"] | |
// } | |
// ] | |
// } |
Author
lisonge
commented
Feb 11, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment