2017-09-03 3 views
2

https://astexplorer.net/#/gist/ad90272020dd0bfb15619d93cca81b66/28d3cf7178271f4f99b10bc9352daa873c2f2b20코드의 첫 번째 라인은 파일을 통해 다른 경우 방법에 insertbefore 작동합니까 파일

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

의 시작 부분에 라인을 삽입 할 jscodeshift를 사용하는 방법에 대해 설명합니다. 예 : (변수 선언, 임포트 문)

답변

2

의 노드가 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); // begining of file 
    }   

    return root.toSource(); 
} 
+0

'캐스트'가 무엇인지 모르겠지만 내 포인트가 누락되었다고 생각합니다. 파일이 변수 선언 대신 가져 오기 명령문으로 시작한다면 어떻게 될까요? 처음에 삽입을 총괄적으로 어떻게 말합니까? 지금까지 j.program()으로 다시 빌드하여이 작업을 수행 할 수있었습니다. – user2167582

+0

또한 삽입하는 방법은 다음과 같습니다. 당신이 단지 노드를 삽입 할 수 없다는 것은 꽤 이상한 것처럼 보입니다. – user2167582

+1

@ user2167582 당신이 요청한 것을 해결했습니다 :) 당신은 insertBefore를 사용하려고합니다. 구조체 인 경우 처음부터 sone literal을 추가하기 만하면 insertAt 0을 사용할 수 있습니다. – bluehipy

1

최고 내가 지금까지 가지고있는 해결책은 첫 번째 앞에 삽입하는 것이다. j.Declaration,

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