import 方式隨心轉(zhuǎn),感受 Babel 插件的威力
本文轉(zhuǎn)載自微信公眾號(hào)「神光的編程秘籍」,作者神說(shuō)要有光zxg 。轉(zhuǎn)載本文請(qǐng)聯(lián)系神光的編程秘籍公眾號(hào)。
當(dāng)我們 import 一個(gè)模塊的時(shí)候,可以這樣默認(rèn)引入:
- import path from 'path';
- path.join('a', 'b');
- function func() {
- const sep = 'aaa';
- console.log(path.sep);
- }
也可以這樣解構(gòu)引入:
- import { join, sep as _sep } from 'path';
- join('a', 'b');
- function func() {
- const sep = 'aaa';
- console.log(_sep);
- }
第一種默認(rèn)引入叫 default import,第二種解構(gòu)引入叫 named import。
不知道大家習(xí)慣用哪一種。
如果有個(gè)需求,讓你把所有的 default import 轉(zhuǎn)成 named import,你會(huì)怎么做呢?
可能你會(huì)說(shuō)這個(gè)不就是找到所有用到引入變量的地方,修改成直接調(diào)用方法,然后那些方法名以解構(gòu)的方式寫在 import 語(yǔ)句里么。
但如果說(shuō)要改的項(xiàng)目有 100 多個(gè)這種文件呢?(觸發(fā) treeshking 要這樣改)
這時(shí)候就可以考慮 babel 插件了,它很適合做這種有規(guī)律且數(shù)量龐大的代碼的自動(dòng)修改。
讓我們通過(guò)這個(gè)例子感受下 babel 插件的威力吧。
因?yàn)榇a比較多,大家可能沒(méi)耐心看,要不我們先看效果吧:
測(cè)試效果
輸入代碼是這樣:
- import path from 'path';
- path.join('a', 'b');
- function func() {
- const sep = 'aaa';
- console.log(path.sep);
- }
我們引入該 babel 插件,讀取輸入代碼并做轉(zhuǎn)換:
- const { transformFileSync } = require('@babel/core');
- const importTransformPlugin = require('./plugin/importTransform');
- const path = require('path');
- const { code } = transformFileSync(path.join(__dirname, './sourceCode.js'), {
- plugins: [[importTransformPlugin]]
- });
- console.log(code);
打印如下:
我們完成了 default import 到 named import 的自動(dòng)轉(zhuǎn)換。
可能有的同學(xué)擔(dān)心重名問(wèn)題,我們測(cè)試一下:
可以看到,插件已經(jīng)處理了重名問(wèn)題。
思路分析
import 語(yǔ)句中間的部分叫做 specifier,我們可以通過(guò) astexplorer.net 來(lái)可視化的查看它的 AST。
比如這樣一條 import 語(yǔ)句:
- import React, {useState as test, useEffect} from 'react';
它對(duì)應(yīng)的 AST 是這樣的:
也就是說(shuō)默認(rèn) import 是 ImportDefaultSpecifier,而解構(gòu) import 是 ImportSpecifier
ImportSpecifier 語(yǔ)句有 local 和 imported 屬性,分別代表引入的名字和重命名后的名字:
那我們的目的明確了,就是把 ImportDefaultSpecifier 轉(zhuǎn)成 ImportSpecifier,并且使用到的屬性方法來(lái)設(shè)置 imported 屬性,需要重命名的還要設(shè)置下 local 屬性。
怎么知道使用到哪些屬性方法呢?也就是如何分析變量的引用呢?
babel 提供了 scope 的 api,用于作用域分析,可以拿到作用域中的聲明,和所有引用這個(gè)聲明的地方。
比如這里就可以用 scope.getBinding 方法拿到該變量的聲明:
- const binding = scope.getBinding('path');
然后用 binding.references 就可以拿到所有引用這個(gè)聲明的地方,也就是 path.join 和 path.sep。
之后就可以把這兩處引用改為直接的方法調(diào)用,然后修改下 import 語(yǔ)句為解構(gòu)就可以了。
我們總結(jié)一下步驟:
- 找到 import 語(yǔ)句中的 ImportDefaultSpecifier
- 拿到 ImportDefaultSpecifier 在作用域的聲明(binding)
- 找到所有引用該聲明的地方(reference)
- 修改各處引用為直接調(diào)用函數(shù)的形式,收集函數(shù)名
- 如果作用域中有重名的變量,則生成一個(gè)唯一的函數(shù)名
- 根據(jù)收集的函數(shù)名來(lái)修改 ImportDefaultSpecifier 為 ImportSpecifier
原理大概過(guò)了一遍,我們來(lái)寫下代碼
代碼實(shí)現(xiàn)
babel 插件是函數(shù)返回對(duì)象的形式,返回的對(duì)象中主要是通過(guò) visitor 屬性來(lái)指定對(duì)什么 AST 做什么處理。
我們搭一個(gè) babel 插件的骨架:
- const { declare } = require('@babel/helper-plugin-utils');
- const importTransformPlugin = declare((api, options, dirname) => {
- api.assertVersion(7);
- return {
- visitor: {
- ImportDeclaration(path) {
- }
- }
- }
- });
- module.exports = importTransformPlugin;
這里我們要處理的是 import 語(yǔ)句 ImportDeclaration。
@babel/helper-plugin-utils 包的 declare 方法的作用是給 api 擴(kuò)充一個(gè) assertVersion 方法。而 assertVersion 的作用是如果這個(gè)插件工作在了 babel6 上就會(huì)報(bào)錯(cuò)說(shuō)這個(gè)插件只能用在 babel7,可以避免報(bào)的錯(cuò)看不懂。
path 是用于操作 AST 的一些 api,而且也保留了 node 之間的關(guān)聯(lián),比如 parent、sibling 等。
接下來(lái)進(jìn)入正題:
我們要先取出 specifiers 的部分,然后找出 ImportDefaultSpecifier:
- ImportDeclaration(path) {
- // 找到 import 語(yǔ)句中的 default import
- const importDefaultSpecifiers = path.node.specifiers.filter(item => api.types.isImportDefaultSpecifier(item));
- // 對(duì)每個(gè) default import 做轉(zhuǎn)換
- importDefaultSpecifiers.forEach(defaultSpecifier => {
- });
- }
然后對(duì)每一個(gè) default import 都要根據(jù)在作用域中的聲明找到所有引用的地方:
- // import 變量的名字
- const importId = defaultSpecifier.local.name;
- // 該變量的聲明
- const binding = path.scope.getBinding(importId);
- binding.referencePaths.forEach(referencePath=> {
- });
然后對(duì)每個(gè)引用到該 import 的地方都做修改,改為直接調(diào)用函數(shù),并且把函數(shù)名收集起來(lái)。這里要注意的是,如果作用域中有同名變量還要生成一個(gè)新的唯一 id。
- // 該變量的聲明
- const binding = path.scope.getBinding(importId);
- const referedIds = [];
- const transformedIds = [];
- // 收集所有引用該聲明的地方的方法名
- binding.referencePaths.forEach(referencePath=> {
- const currentPath = referencePath.parentPath;
- const methodName = currentPath.node.property.name;
- // 之前方法名
- referedIds.push(currentPath.node.property);
- if (!currentPath.scope.getBinding(methodName)) {// 如果作用域沒(méi)有重名變量
- const methodNameNode = currentPath.node.property;
- currentPath.replaceWith(methodNameNode);
- transformedIds.push(methodNameNode); // 轉(zhuǎn)換后的方法名
- } else {// 如果作用域有重名變量
- const newMethodName = referencePath.scope.generateUidIdentifier(methodName);
- currentPath.replaceWith(newMethodName);
- transformedIds.push(newMethodName); // 轉(zhuǎn)換后的方法名
- }
- });
這部分邏輯比較多,著重講一下。
我們對(duì)每個(gè)引用了該變量的地方都要記錄下引用了哪個(gè)方法,比如 path.join、path.sep 就引用了 join 和 sep 方法。
然后就要把 path.join 替換成 join,把 path.sep 替換成 sep。
如果作用域中有了 join 或者 sep 的聲明,需要生成一個(gè)新的 id,并且記錄下新的 id 是什么。
收集了所有的方法名,就可以修改 import 語(yǔ)句了:
- // 轉(zhuǎn)換 import 語(yǔ)句為 named import
- const newSpecifiers = referedIds.map((id, index) => api.types.ImportSpecifier(transformedIds[index], id));
- path.node.specifiers = newSpecifiers;
沒(méi)有 babel 插件基礎(chǔ)可能看的有點(diǎn)暈,沒(méi)關(guān)系,知道他是做啥的就行。我們接下來(lái)試下效果。
思考和代碼
我們做了 default import 到 named import 的自動(dòng)轉(zhuǎn)換,其實(shí)反過(guò)來(lái)也一樣,不也是分析 scope 的 binding 和 reference,然后去修改 AST 么?感興趣的同學(xué)可以試下反過(guò)來(lái)轉(zhuǎn)換怎么寫。
插件全部代碼如下:
- const { declare } = require('@babel/helper-plugin-utils');
- const importTransformPlugin = declare((api, options, dirname) => {
- api.assertVersion(7);
- return {
- visitor: {
- ImportDeclaration(path) {
- // 找到 import 語(yǔ)句中的 default import
- const importDefaultSpecifiers = path.node.specifiers.filter(item => api.types.isImportDefaultSpecifier(item));
- // 對(duì)每個(gè) default import 做轉(zhuǎn)換
- importDefaultSpecifiers.forEach(defaultSpecifier => {
- // import 變量的名字
- const importId = defaultSpecifier.local.name;
- // 該變量的聲明
- const binding = path.scope.getBinding(importId);
- const referedIds = [];
- const transformedIds = [];
- // 收集所有引用該聲明的地方的方法名
- binding.referencePaths.forEach(referencePath=> {
- const currentPath = referencePath.parentPath;
- const methodName = currentPath.node.property.name;
- // 之前方法名
- referedIds.push(currentPath.node.property);
- if (!currentPath.scope.getBinding(methodName)) {// 如果作用域沒(méi)有重名變量
- const methodNameNode = currentPath.node.property;
- currentPath.replaceWith(methodNameNode);
- transformedIds.push(methodNameNode); // 轉(zhuǎn)換后的方法名
- } else {// 如果作用域有重名變量
- const newMethodName = referencePath.scope.generateUidIdentifier(methodName);
- currentPath.replaceWith(newMethodName);
- transformedIds.push(newMethodName); // 轉(zhuǎn)換后的方法名
- }
- });
- // 轉(zhuǎn)換 import 語(yǔ)句為 named import
- const newSpecifiers = referedIds.map((id, index) => api.types.ImportSpecifier(transformedIds[index], id));
- path.node.specifiers = newSpecifiers;
- });
- }
- }
- }
- });
- module.exports = importTransformPlugin;
總結(jié)
我們要做 default import 轉(zhuǎn) named import,也就是 ImportDefaultSpecifier 轉(zhuǎn) ImportSpecifier,要通過(guò) scope 的 api 分析 binding 和 reference,找到所有引用的地方,替換成直接調(diào)用函數(shù)的形式,然后再去修改 import 語(yǔ)句的 AST 就可以了。
babel 插件特別適合做這種有規(guī)律且轉(zhuǎn)換量比較大的需求,在一些場(chǎng)景下是有很大的威力的。