webpack:babel插件开发

795 阅读2分钟

需求

不同环境下前端使用不同的配置

babel插件

Babel的工作过程

Babel的处理过程主要为3个:解析(parse)转换(transform)生成(generate)

  • 解析

    解析主要包含两个过程:词法分析和语法分析,输入是代码字符串,输出是AST。

  • 转换

    处理AST。处理工具、插件等就是在这个过程中介入,将代码按照需求进行转换。

  • 生成

    遍历AST,输出代码字符串。

解析和生成过程,都有Babel都为我们处理得很好了,我们要做的就是在 转换 过程中搞事情,进行个性化的定制开发。

尝试开发

npm安装开发中用到的依赖 @babel/core(模拟运行babel)和 @babel/types(对语法树进行操作):

npm install @babel/core @babel/types

咱们晓得babel能编译es6代码,例如最根底的const和箭头函数:

// es2015 的 const 和 arrow function
const add = (a, b) => a + b;

// Babel 转译后
var add = function add(a, b) {
  return a + b;
};

咱们能够到 astexplorer 查看生成的语法树:

{
  "type": "Program",
  "body": [
    {
      "type": "VariableDeclaration", // 变量申明
      "declarations": [ // 具体申明
        {
          "type": "VariableDeclarator", // 变量申明
          "id": {
            "type": "Identifier", // 标识符(最根底的)
            "name": "add" // 函数名
          },
          "init": {
            "type": "ArrowFunctionExpression", // 箭头函数
            "id": null,
            "expression": true,
            "generator": false,
            "params": [ // 参数
              {
                "type": "Identifier",
                "name": "a"
              },
              {
                "type": "Identifier",
                "name": "b"
              }
            ],
            "body": { // 函数体
              "type": "BinaryExpression", // 二项式
              "left": { // 二项式右边
                "type": "Identifier",
                "name": "a"
              },
              "operator": "+", // 二项式运算符
              "right": { // 二项式左边
                "type": "Identifier",
                "name": "b"
              }
            }
          }
        }
      ],
      "kind": "const"
    }
  ],
  "sourceType": "module"
}

我们可以做一简单箭头函数转换成普通函数

const types = require('@babel/types');
const babel = require('@babel/core');

let code = `let add = (a, b)=>{return a+b}`;
let ArrowPlugins = {
visitor: {
    ArrowFunctionExpression(path) {
      let { node } = path;
      let body = node.body;
      let params = node.params;
      let r = types.functionExpression(null, params, body, false, false);
      path.replaceWith(r);
    }
  }
}
babel.transform(code, {
  filename: 'test.js',
  plugins: [
    ArrowPlugins
  ]
}, (err, result) => {
  console.log(err)
  console.log('++++++++++ test +++++++++');
  console.log(result.code);
  console.log('++++++++++ test end +++++++++');
})

运行后输出结果

undefined
++++++++++ test end +++++++++
var add = function add(a, b) { return a + b; };
++++++++++ test +++++++++

需求开发

const env = process.env.CI_FE_ENV;
const importPlugin = ({ types }) => {
  return {
    visitor: {

      ImportDeclaration(path, source) {
        let node = path.node
        
        // 判断只有导入的文件为‘@/config’的时候才进行替换
        if (node.source.value === '@/config') {
          let specifiers = []
          node.specifiers.map((specifier) => {
          
            // 引入默认配置
            let defaultLocal = types.importDefaultSpecifier(types.identifier('__default_config'));
            const newimport = types.importDeclaration([defaultLocal],types.stringLiteral(node.source.value+"/default.config.js"))
            specifiers.push(newimport)
            
            // 引入环境对应配置
            let envLocal = types.importDefaultSpecifier(types.identifier('__env_config'));
            const newimport2 = types.importDeclaration([envLocal],types.stringLiteral(node.source.value+`/${env}.config.js`))
            specifiers.push(newimport2)
            
            // 进行配置合并
            const newconfigVar = types.variableDeclaration("const", [
              types.variableDeclarator(specifier.local, 
                types.objectExpression([
                  types.spreadElement(types.identifier('__default_config')),
                  types.spreadElement(types.identifier('__env_config')),
                ]),
              ),
            ]);
            specifiers.push(newconfigVar)
          });
          
          // 替换当前绑定
          path.replaceWithMultiple(specifiers)

        }
      },
    },
  };
}