Babel code conversion is done by applying plug-ins or presets to configuration files.

The use of plug-in

If the plug-in is on NPM, you can pass in the name of the plug-in and Babel will check if it is installed on node_modules. The plugins added in the plugins configuration option take an array.

{
  "plugins": ["babel-plugin-myPlugin"."@babel/plugin-transform-runtime"]}Copy the code

You can also specify relative/absolute paths for plug-ins {“plugins”: [“./node_modules/ ASdf /plugin”]} for more details on configuring plug-ins or default paths, click Name Normalization

The transformation plug-in

These plug-ins are used to transform your code

The transformation plug-in will enable the corresponding syntax look-up, so you don’t have to specify both.

Grammar plug-in

Most syntax can be converted by Babel. In rare cases (if the conversion has not been implemented, or there is no default method), you can use plug-ins such as @babel/plugin-syntax-bigint that only allows Babel to parse the syntax of pending types. Or maybe you want to keep the source code because you only want Babel to do code analysis or Codemods.

Note: If you already use the appropriate transformation plug-in, you do not need to specify the syntax plug-in because it will automatically enable it.

Alternatively, you can pass any plugins parameters through the Babel parser:

Your. Babelrc:

{
  "parserOpts": {
    "plugins": ["jsx"."flow"]}}Copy the code

Order of plug-ins

The order of the plug-ins is important

This means that if both transformation plug-ins will process a piece of code in the program, they will be executed sequentially according to the transformation plug-in or the preset order.

  • The plug-in runs before default
  • The order of plug-ins is front to back
  • The default order is from back to front

Such as:

  • Plug-in:

    {
         "plugins": ["transform-decorators-legacy"."transform-class-properties"]}Copy the code

    Transform-decorators-legacy before transform-class-properties.

  • The default:

      {
          "presets": ["@babel/preset-env"."@babel/preset-react"]}Copy the code

    This is run in the following order: @babel/preset-react and then @babel/preset-env.

The plug-in parameters

Both plug-ins and presets accept parameters, which consist of an array of plug-in names and parameter objects that can be set in a configuration file. If no arguments are specified, the following methods are the same:

{
  "plugins": ["pluginA"["pluginA"], ["pluginA"}, {}]]Copy the code

To specify parameters, pass an object with the parameter name as the key.

{
  "plugins": [["transform-async-to-module-method",
      {
        "module": "bluebird"."method": "coroutine"}}]]Copy the code

The default Settings work exactly the same way:

{
  "presets": [["env",
      {
        "loose": true."modules": false}}]]Copy the code