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

use*_*582 8 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();
}
Run Code Online (Sandbox Code Playgroud)

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

blu*_*ipy 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()
}
Run Code Online (Sandbox Code Playgroud)

编辑

为了您的澄清.

如果要插入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()
}
Run Code Online (Sandbox Code Playgroud)

如果要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();
}
Run Code Online (Sandbox Code Playgroud)