2016-03-10 36 views
0

假設你有一個文件:如何導入添加到該文件與巴貝爾

AddReactImport(); 

和插件:

export default function ({types: t }) { 
    return { 
    visitor: { 
     CallExpression(p) { 
     if (p.node.callee.name === "AddReactImport") { 
      // add import if it's not there 
     } 
     } 
    } 
    }; 
} 

你如何在文件的頂部添加import React from 'react'; /樹如果它不在那裏。

我認爲比答案更重要的是你如何找出如何去做。請告訴我,因爲我很難找到有關如何開發Babel插件的信息來源。我現在的來源是:Plugin Handbook,Babel Types,AST Spec, this blog postAST explorer。這感覺就像用英語 - 德語詞典試圖說德語。

回答

0
export default function ({types: t }) { 
    return { 
    visitor: { 
     Program(path) { 
     const identifier = t.identifier('React'); 
     const importDefaultSpecifier = t.importDefaultSpecifier(identifier); 
     const importDeclaration = t.importDeclaration([importDefaultSpecifier], t.stringLiteral('react')); 
     path.unshiftContainer('body', importDeclaration); 
     } 
    } 
    }; 
}