gkz / grasp

JavaScript structural search, replace, and refactor
http://graspjs.com
MIT License
1.28k stars 33 forks source link

How to match import specifier by id? #106

Closed kristianmandrup closed 7 years ago

kristianmandrup commented 7 years ago

As per https://github.com/estools/esquery/issues/50

How do I match import x in the following!?

Error: Expected operator ), but found: {"type":"operator","value":"="}

let importStmt = `import x from 'x'`

const find = `import-dec[specifiers=(id=#x)]`
const replace = `import y from 'x'`
const replacer = grasp.replace('squery', find, replace)
let result = replacer(importStmt)

Or why not?

import-dec[specifiers[id=#x]] OR import-dec[specifiers=(import-default-specifier[id=#x])]

TypeError: Cannot read property 'nodes' of undefined (last attempt)

From esprima parser

    "body": [
        {
            "type": "ImportDeclaration",
            "specifiers": [
                {
                    "type": "ImportDefaultSpecifier",
                    "local": {
                        "type": "Identifier",
                        "name": "x"
                    }
                }
            ],
            "source": {
                "type": "Literal",
                "value": "./x",
                "raw": "'./x'"
            }
        },
kristianmandrup commented 7 years ago

Finally getting somewhere, but not quite...

const find = `import-dec > specifiers import-default-specifier[id=#x]`
const replace = `y`

const replacer = grasp.replace('squery', find, replace)

How do I select on the outer import node and not the specifier? Even in this case, the specifier is not replaced by y

gkz commented 7 years ago

Can you give a better example of what you want?

ie. this is the code you have, this is what you want matched. It is unclear from your post

Are you wanting to use grasp "import-dec! import-default-specifier[local=#x]"? ie using http://www.graspjs.com/docs/squery/#subject

kristianmandrup commented 7 years ago

oh, wow! Thanks @gkz exactly what I wanted. I wish you had some more examples on how to use the query/select syntax to such great effect for more complex queries. Cheers!

kristianmandrup commented 7 years ago

Perfect! It works like a charm! Thanks again :)