Skip to content

[Bug]: @babel/parser fails when loading options programaticallyΒ #14082

Closed
@mskelton

Description

πŸ’»

  • Would you like to work on a fix?

How are you using Babel?

Programmatic API (babel.transform, babel.parse)

Input code

console.log('test')

Configuration file name

babel.config.js

Configuration

module.exports = {
  presets: ["@babel/preset-env"],
};

Current and expected behavior

When parsing with the following code:

const { parse } = require("@babel/parser");
const { loadOptions } = require("@babel/core");

const input = `
console.log('mark')
`;

parse(input, loadOptions())

Babel will fail with the following error:

> babel-repro@1.0.0 start
> node ./parse.js

/Users/mskelton/dev/babel-repro/node_modules/@babel/parser/lib/index.js:10658
      const [pluginName, pluginOptions] = p;
                                          ^

TypeError: p is not iterable
    at /Users/mskelton/dev/babel-repro/node_modules/@babel/parser/lib/index.js:10658:43
    at Array.some (<anonymous>)
    at hasPlugin (/Users/mskelton/dev/babel-repro/node_modules/@babel/parser/lib/index.js:10654:18)
    at validatePlugins (/Users/mskelton/dev/babel-repro/node_modules/@babel/parser/lib/index.js:10693:7)
    at getParser (/Users/mskelton/dev/babel-repro/node_modules/@babel/parser/lib/index.js:15287:5)
    at parse (/Users/mskelton/dev/babel-repro/node_modules/@babel/parser/lib/index.js:15258:12)
    at Object.<anonymous> (/Users/mskelton/dev/babel-repro/parse.js:8:13)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)

Environment

System:

  • OS: macOS 11.6.1

Binaries:

  • Node: 16.13.1 - ~/.local/share/nvm/v16.13.1/bin/node
  • Yarn: 1.22.17 - /usr/local/bin/yarn
  • npm: 8.1.2 - ~/.local/share/nvm/v16.13.1/bin/npm

npmPackages:

  • @babel/core: ^7.16.5 => 7.16.5
  • @babel/parser: ^7.16.6 => 7.16.6
  • @babel/preset-env: ^7.16.5 => 7.16.5

Possible solution

Update hasPlugin in packages/babel-parser/src/plugin-utils.js to test all types of plugin objects (string, array, ConfigItem, Plugin, etc.).

Additional context

A recent change to hasPlugin in #13982 broke certain programatic usages of the Babel API when loading config from a babel.config.js file. This does not occur when loading from a .babelrc file interestingly enough.

This is used in the wild as it is the cause of https://github.com/stylelint/postcss-css-in-js/issues/247.

A full working example is available here: https://github.com/mskelton/babel-repro/blob/working/parse.js

Metadata

Assignees

No one assigned

    Labels

    i: needs triageoutdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions