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

标签 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 如何工作。例如(变量声明,导入语句)

最佳答案

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

如果你想在 import 声明之后添加 use 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); // beginning of file
    }         

    return root.toSource();
}

关于javascript - 如何使用jscodeshift在文件开头插入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46021203/

相关文章:

javascript - 为什么就地编辑表单与显示版本一起呈现而不是动态呈现?

javascript - module.exports 中 "this"的范围

javascript - 映射/过滤/减少数组

jscodeshift - 如何在检查模式下启动 jscodeshift?

javascript - 有没有一种方法可以在 jQuery 中克隆数组?

java - 如何构建 Java 类的元模型以通过代码分析生成服务图?

typescript - 使用 TypeScript API 查找类型引用

Python 3,ast.literal_eval(node_or_string) 中是否有任何已知的安全漏洞?

javascript - 如何将 React Typescript 解析为 jscodeshift 代码