如何使用jscodeshift在文件的开头插入一行

时间:2017-09-03 07:27:47

标签: javascript abstract-syntax-tree jscodeshift

https://astexplorer.net/#/gist/ad90272020dd0bfb15619d93cca81b66/28d3cf7178271f4f99b10bc9352daa873c2f2b20

// file
var a = "a" // what if this is import statement?

// jscodeshift
export default (file, api) => {
  const j = api.jscodeshift;

  const root = j(file.source);

  root.find(j.VariableDeclaration)
    .insertBefore("use strict");
  return root.toSource();
}

如果第一行代码在文件中不同,insertBefore如何工作。例如(变量声明,导入声明)

2 个答案:

答案 0 :(得分:9)

看起来您必须"cast" jscodeshift的节点。

解决方案是:

export default (file, api) => {
  const j = api.jscodeshift

  const root = j(file.source)

  j(root.find(j.VariableDeclaration).at(0).get())
    .insertBefore(
      '"use strict";'
    )
  return root.toSource()
}

修改

供您澄清。

如果您想在文件的开头插入use strict,无论如何:

export default (file, api) => {
    const j = api.jscodeshift
    const s = '"use strict";';
    const root = j(file.source)

    root.get().node.program.body.unshift(s);  

    return root.toSource()
}

如果您想在use strict声明后添加import,如果有的话:

export default (file, api) => {
    const j = api.jscodeshift
    const s = '"use strict";';
    const root = j(file.source);
    const imports = root.find(j.ImportDeclaration);
    const n = imports.length;

    if(n){
        //j(imports.at(0).get()).insertBefore(s); // before the imports
       j(imports.at(n-1).get()).insertAfter(s); // after the imports
    }else{
       root.get().node.program.body.unshift(s); // begining of file
    }         

    return root.toSource();
}

答案 1 :(得分:1)

我到目前为止最好的解决方案是在第一个j.Declaration之前插入

j(root.find(j.Declaration).at(0).get())
 .insertBefore('"use strict";')