compile 阶段收集多语言词条

34 阅读1分钟

Compile 阶段收集词条

const babel = require('@babel/core');
const babelplugin = require('./babelplugin.js');

const code = `
    import { useAssetsTranslation } from '@/utils/i18Util';
    import { useMemo } from 'react';
    
    export default function Layout() {
      console.log('asset--Layout render');
    
      const aa = useMemo(() => {
        return <div>{t('12313')}</div>;
      }, []);
    
      const { t } = useAssetsTranslation();
      const { t: t1 } = useTranslation();
      const asd = useTranslation('web-ddd');
    
     const btnMap = {
        'a': { title: t('rfq.buy', { val1: 'hhh', val2: 'ee' }), bg: 'bg-g00' },
        'b': { title: t('rfq.sell', 'asdasd'), bg: 'bg-r00' },
        'c': { title: t('rfq.convert_ensure', '23456789o0p['), bg: 'bg-alwaysBlack' },
      };
    
      return (
        <>
          {t('111asset_fiat.deposit_title')}
          {t1('222asset_fiat.deposit_title')}
          {asd.t('333asset_fiat.deposit_title')}
          hahhah
          {aa}
        </>
      );
    }
    
`;
const ast1 = babel.transform(code, {
  presets: ['@babel/preset-react'],
  plugins: [
    [
      babelplugin,
      {
        nameSpaceList: [
          { callee: 'useAssetsTranslation', nameSpace: 'asset-lang' },
          { callee: 'useTranslation' },
        ],
        defaultNameSpace: 'web-common-lang',
      },
    ],
  ],
});
// console.log(ast1.code);、
module.exports = ({ types }, options) => {
  const callList = [];

  const nameSpaceList = (options?.nameSpaceList || []).map((itemNameSpace) => {
    return {
      ...itemNameSpace,
      nameSpace: itemNameSpace.nameSpace || options.defaultNameSpace,
    };
  });

  const resultLangKey = new Map();
  return {
    visitor: {
      CallExpression(astPath, state) {
        let calleeStr = astPath.get('callee').toString();

        const isMatch = nameSpaceList.find((name) => calleeStr === name.callee);

        if (isMatch) {
          const astPathArg = astPath.get('arguments');
          let calleeArg = astPathArg.length
            ? astPath.get('arguments.0').get('value').node
            : '';
          const nameSpace = calleeArg ? calleeArg : isMatch.nameSpace;

          const parentAst = astPath.parentPath.get('id');

          if (types.isObjectPattern(parentAst)) {
            const propertiesVal = parentAst
              .get('properties.0')
              .get('value')
              .toString();
            callList.push({ nameSpace, callee: propertiesVal });
          } else {
            callList.push({ nameSpace, callee: parentAst.toString() + '.t' });
          }
        }

        const rootPath = astPath.findParent((path) => path.isProgram());
        rootPath.traverse({
          CallExpression(path) {
            let calleeStr = path.get('callee').toString();
            const isMatchCallee = callList.find(
              (callListItemm) => callListItemm.callee === calleeStr,
            );
            if (isMatchCallee) {
              const matchNameSpace = isMatchCallee.nameSpace;
              const calleeArgsStr = path.get('arguments.0').get('value').node;

              if (resultLangKey.has(matchNameSpace)) {
                resultLangKey.get(matchNameSpace).add(calleeArgsStr);
              } else {
                resultLangKey.set(matchNameSpace, new Set());
              }
            }
          },
        });
      },
      Program: {
        exit() {
          console.log(resultLangKey, 'resultLangKey');
        },
      },
    },
  };
};

效果: