// 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如何工作。例如(变量声明,导入声明)
答案 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";')