gkz / grasp

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

Please add better usage examples #102

Open mandricore opened 7 years ago

mandricore commented 7 years ago

I'm trying to make the following work, taking the examples from your main docs on lib usage

This works

import test from 'ava'
import grasp from 'grasp'
import _ from 'lodash'
import path from 'path'

const reqCode = `var Abe = require('abe')`
const log = console.log

let processed = grasp.replace('squery', 'call[callee=#require]', (getRaw, node, query) => {
  let req = query('.args')[0]
  let importCode = 'import ' + _.camelCase(path.basename(req.value, '.js')) + ' from ' + getRaw(req)
  log('import code', importCode)
  return importCode
}, reqCode)

test('replace require with import', t => {
  log('code y', processed)
  t.is(processed, `var Abe = import abe from 'abe'`)
})

But here I get an error

import test from 'ava'
import grasp from 'grasp'

let code = `var a = 1 + 2`

const replacer = grasp.replace('equery', '__ + __', '{{.l}} - {{.r}}')
let processed = replacer(code)

const log = console.log

test('replace + with -', t => {
  log('code x', processed)
  t.is(processed, `var a = 1 - 2`)
})

Why is .l not working? deprecated?

Test runner result:


(input): Error during replacement. Error processing selector '.l'..
code x undefined```

Please advice
gkz commented 7 years ago

You are mixing equery selector with squery replacement selector. There is not option allowing you to mix them at the moment. If you want to use equery to select, you must use its replacement syntax. Eg.

const grasp = require("grasp");
let code = `var a = 1 + 2`;

const replacer = grasp.replace('equery', '$a + $b', '{{a}} - {{b}}');
let processed = replacer(code);
console.log(processed);

.

gkz commented 7 years ago

Actually, I will keep this open as a documentation issue