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

Javascript 如何使用jscodeshift在文件开头插入一行,javascript,abstract-syntax-tree,jscodeshift,Javascript,Abstract Syntax Tree,Jscodeshift,//文件 var a=“a”//如果这是导入语句怎么办? //jscodeshift 导出默认值(文件、api)=>{ const j=api.jscodeshift; const root=j(file.source); root.find(j.VariableDeclaration) .insertBefore(“严格使用”); 返回root.toSource(); } 如果文件中的第一行代码不同,insertBefore如何工作。e、 g.(变量声明、导入语句)看起来您必须将节点转换到j

//文件
var a=“a”//如果这是导入语句怎么办?
//jscodeshift
导出默认值(文件、api)=>{
const j=api.jscodeshift;
const root=j(file.source);
root.find(j.VariableDeclaration)
.insertBefore(“严格使用”);
返回root.toSource();
}

如果文件中的第一行代码不同,insertBefore如何工作。e、 g.(变量声明、导入语句)

看起来您必须将节点转换到
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()
}
编辑

谢谢你的澄清

如果要在文件开头插入
,请使用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()
}
如果要在
导入
声明后添加
使用strict
,如果有:

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();
}

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

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

我不确定
cast
的作用,但我认为您没有领会我的意思,如果文件以import语句而不是变量声明开始,该怎么办?你一般怎么说在开头插入?到目前为止,我只能通过使用j.program()重建来实现这一点。他们也希望您这样插入吗?看起来很奇怪,你不能只插入一个节点。@user2167582我解决了你的问题:)你以前试过使用insert82。如果您只是想在结构的开头添加一个文字,那么可以使用insertAt 0。但是如果文件以import语句开头,那么如何使用insert at?@user2167582您可以测试这种情况并决定如何操作。