facebook / jscodeshift

A JavaScript codemod toolkit.
https://jscodeshift.com
MIT License
9.14k stars 471 forks source link

jscodeshift node api example #398

Open aneurysmjs opened 3 years ago

aneurysmjs commented 3 years ago

Hi everybody, I've seen some developers wondering how to run jscodeshift without CLI, there are some issues but they're very simple, so If someone wants to effectively run it with options, here's an example.

Привет всем, я видел, как некоторые разработчики задаются вопросом, как запустить jscodeshift без CLI, есть некоторые проблемы, но они очень простые, поэтому, если кто-то хочет эффективно запускать его с параметрами, вот пример.

const path = require('path');
const Runner = require('jscodeshift/src/Runner');

// just the paths of the files to apply the transformation
// просто пути к файлам, чтобы применить преобразование
const paths = [ 'path/to/example1.js', 'path/to/example2.js'];

/**
 * taken from
 * взято из
 * @link https://github.com/facebook/jscodeshift/blob/48f5d6d6e5e769639b958f1a955c83c68157a5fa/bin/jscodeshift.js#L18
 */
const options = {
  transform: 'path/to/transformerFile.js',
  verbose: 0,
  dry: false,
  print: true,
  babel: true,
  extensions: 'js',
  ignorePattern: [],
  ignoreConfig: [],
  runInBand: false,
  silent: false,
  parser: 'babel',
  stdin: false
}

/**
 * taken from
 * взято из
 * @link https://github.com/facebook/jscodeshift/blob/48f5d6d6e5e769639b958f1a955c83c68157a5fa/bin/jscodeshift.js#L135
 */
Runner.run(
  /^https?/.test(options.transform) ? options.transform : path.resolve(options.transform),
  paths,
  options
);

the rest depends on how it will be used остальное зависит от того, как будет использоваться

related #343

related #179

abernier commented 2 years ago

would be great to make this issue a PR about adding this to official doc

abernier commented 2 years ago

Actually, this is even better, run() returning a promise you can:

const res = await Runner.run(...)

console.log(res)
/*
{
  stats: {},
  timeElapsed: '0.001',
  error: 0,
  ok: 0,
  nochange: 0,
  skip: 0
}
*/