自制簡單的babel插件

示例

一個用於生產時 去掉代碼中 全部的打印代碼,如 console.log('亂七八糟')html

待轉換的文件 test.jsnode

console.log('你好');
let a = 'as';

babel轉換文件  plugin.jsgit

module.exports = function (babel) {

    const { types: t, template } = babel;

    const keyPathVisitor = (node , properties) => {
        let temp = node
        for(let item of properties) {
            if (temp[item])
                temp = temp[item]
            else {
                temp = null
                break
            }
        }
        return temp
    }

    const visitor = {
        //須要訪問的節點名
        //訪問器默認會被注入兩個參數 path(類比成dom),state
        ExpressionStatement(path, state) {
            if (process.env.NODE_ENV === 'production') {
              const node = path.node;
              //延當前節點向內部訪問,判斷是否符合console解析出的ast的特徵
              const expressionNode = keyPathVisitor(node, ['expression']);
              const isCallExpression = expressionNode.type === 'CallExpression';
              if (isCallExpression) {
                const objectName = keyPathVisitor(expressionNode, ['callee', 'object', 'name']);
                const prototypeName = keyPathVisitor(expressionNode, ['callee', 'property', 'name']);
                if (objectName === 'console' && prototypeName === 'log') {
                  //若是符合上述條件,直接移除該節點
                  path.remove();
                }
              }
            }

        }
    };

    return {
        visitor
    };
};

 

進行轉換:

使用babel-cli 進行手動轉換,安裝  npm i babel-cli -Des6

一、指定轉換文件  npx babel --plugins ./plugin.js test.js。github

成功轉換express

二、用.babelrc 配置 進行轉換。npm

{
  "plugins": [
    "./pluginLog" // babel轉換文件所在位置
  ]
}
E:\workspace\babel\test>npx babel test.js

let a = 'as';

 

寫在文末:

所謂的babel插件,就是用來 轉換代碼。源代碼 到 源代碼。具體來講 就是 將環境(如瀏覽器)不識別的代碼轉換成 能被支持的代碼。segmentfault

如 es2015 (將es6 轉換成es5),babel-plugin-compoment (餓了麼組件的 按需加載功能)。瀏覽器

任何 代碼均可以按照 咱們想要的 形式轉換(即便轉換成爲不被識別,有毒 哈哈)。轉換的關鍵是 操做 ast 。babel

你須要先將 被轉換的源代碼 解析 出它的 ast結構,而後針對ast進行操做(是個大工程)。

解析出ast結構:https://astexplorer.net/

操做ast:https://github.com/jamiebuilds/babel-handbook/blob/master/translations/zh-Hans/plugin-handbook.md#toc-visiting

參考連接:

http://www.javashuo.com/article/p-hwausoua-kr.html

https://www.cnblogs.com/chyingp/p/how-to-write-a-babel-plugin.html

項目所在位置;

https://github.com/18946168254/babel-test.git

相關文章
相關標籤/搜索