本文介绍了Babel插件运行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL; DR:有没有一种方法可以指定应运行Babel插件的顺序? Babel如何确定此顺序?除了深入了解Babel消息来源,还有其他规范吗?

TL;DR: Is there a way how to specify the order in which the Babel plugins are supposed to be run? How does Babel determine this order? Is there any spec how this works apart from diving into Babel sources?

我正在开发自己的Babel插件.我注意到,当我运行它时,我的插件比其他es2015插件先运行.例如,具有以下代码:

I'm developing my own Babel plugin. I noticed, that when I run it, my plugin is run before other es2015 plugins. For example having code such as:

const a = () => 1

和访问者,例如:

visitor: {
  ArrowFunctionExpression(path) {
    console.log('ArrowFunction')
  },
  FunctionExpression(path) {
    console.log('Function')
  },
}

我的插件遵循ArrowFunction(而不是Function).我按照插件在Babel配置中列出的顺序进行操作,但这并没有任何改变:

my plugin observes ArrowFunction (and not Function). I played with the order in which the plugins are listed in Babel configuration, but that didn't change anything:

plugins: ['path_to_myplugin', 'transform-es2015-arrow-functions'],
plugins: ['transform-es2015-arrow-functions', 'path_to_myplugin'],

OTOH,这看起来顺序确实很重要:

OTOH, this looks like the order DOES somehow matter:

https://phabricator.babeljs.io/T6719

----编辑----

---- EDIT ----

我发现如果我按如下方式写我的访客:

I found out that if I writer my visitor as follows:

  ArrowFunctionExpression: {
    enter(path) {
      console.log('ArrowFunction')
    }
  },
  FunctionExpression: {
    exit(path) {
      console.log('Function')
    }
  },

两个函数都被调用.因此,执行顺序看起来是:myplugin_enter-> other_plugin-> myplugin_exit.换句话说,在某些内部管道中,myplugin似乎在other_plugin之前.但是主要问题保持不变-管道中插件的顺序应确定&可以以某种方式配置.

both functions are called. So it looks like the order of execution is: myplugin_enter -> other_plugin -> myplugin_exit. In other words, myplugin seems to be before other_plugin in some internal pipeline. The main question however stays the same - the order of plugins in the pipeline should be determined & configurable somehow.

推荐答案

插件的顺序基于.babelrc中事物的顺序,其中插件在预设之前运行,而每个组都在较早的插件/预设之前运行.

The order of plugins is based on the order of things in your .babelrc with plugins running before presets, and each group running later plugins/presets before earlier ones.

关键是按AST节点排序.每个插件都不能完全遍历,Babel可以并行运行所有插件,一次遍历,每个节点一次处理一个,为每个插件运行每个处理程序.

The key thing though is that the ordering is per AST Node. Each plugin does not do a full traversal, Babel does a single traversal running all plugins in parallel, with each node processed one at a time running each handler for each plugin.

这篇关于Babel插件运行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 08:08