Babel: Replacing ArrowFunctionExpression vs FunctionDeclaration in ExportDefaultDeclaration

走远了吗. 提交于 2020-01-03 19:31:34

问题


Say I have the following code I want to transform:

export default () => {};

The following visitor code works:

export default function ({ types: t }) {
  return {
    visitor: {
      ArrowFunctionExpression(path) {
        if (!path.node.body.directives.some(d => d.value.value === 'inject')) return;
        path.node.body.directives = path.node.body.directives.filter(d => d.value.value !== 'inject');
        path.replaceWith(t.arrayExpression([path.node]));
      }
    }
  };
}

That results in the following output:

export default [() => {}];

Great! Now change the input:

export default function () {
  'inject';
};

And the visitor:

export default function ({types: t}) {
  return {
    visitor: {
      FunctionDeclaration(path) {
        if (!path.node.body.directives.some(d => d.value.value === 'inject')) return;
        path.node.body.directives = path.node.body.directives.filter(d => d.value.value !== 'inject');
        path.replaceWith(t.arrayExpression([path.node]));
      }
    }
  };
}

That produces the following error:

TypeError: unknown: Property elements[0] of ArrayExpression expected node to be of a type ["null","Expression","SpreadElement"] but instead got "FunctionDeclaration"

Okay, so convert the FunctionDeclaration to a FunctionExpression:

export default function ({types: t}) {
  return {
    visitor: {
      FunctionDeclaration(path) {
        if (!path.node.body.directives.some(d => d.value.value === 'inject')) return;
        path.node.body.directives = path.node.body.directives.filter(d => d.value.value !== 'inject');
        path.replaceWith(
          t.arrayExpression([
            t.functionExpression(path.node.id, path.node.params, path.node.body, path.node.generator, path.node.async),
          ])
        );
      }
    }
  };
}

And I get the following error:

TypeError: unknown: Property declaration of ExportDefaultDeclaration expected node to be of a type ["FunctionDeclaration","ClassDeclaration","Expression"] but instead got "ExpressionStatement"

And that is where I'm lost. I'm creating an ArrayExpression just as I was with the default-exported arrow function. Why is it complaining about receiving an ExpressionStatement?

Note, the desired output is as such:

export default [function () {
}];

来源:https://stackoverflow.com/questions/39151261/babel-replacing-arrowfunctionexpression-vs-functiondeclaration-in-exportdefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!