// 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/