Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[writing plugin] SyntaxError: This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' #12468

Closed
1 task
budarin opened this issue Dec 9, 2020 · 18 comments
Labels
i: question outdated A closed issue/PR that is archived due to age. Recommended to make a new issue

Comments

@budarin
Copy link

budarin commented Dec 9, 2020

Bug Report

  • I would like to work on a fix!

Current behavior

Write simple plugin as described in doc, but get the error

Input Code

module.exports = () => ({
  name: 'myPlugin',
  inherits: require("babel-plugin-syntax-jsx"),
  visitor: {
      ...
      const component = template.expression`({children, ...rest}) => <Component {...rest}>{children}</Component>;`;
      path.replaceWith(component());
      ...
  }
});
SyntaxError: This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (2:30)
      1 | (
    > 2 | ({children, ...rest}) => <Component {...rest}>{children}</Component>;
        |                          ^
      3 | )

Expected behavior

success transpilation

Babel Configuration (babel.config.js, .babelrc, package.json#babel, cli command, .eslintrc)

  • Filename: babel.config.js
const isTesting = process.env.NODE_ENV === 'test';
const isDev = process.env.NODE_ENV !== 'production';

module.exports = {
    comments: true,
    presets: [
        [
            '@babel/preset-env',
            {
                loose: true,
                debug: false,
                modules: isTesting ? 'commonjs' : false,
                corejs: {
                    version: 3,
                    proposals: true,
                },
                useBuiltIns: 'usage',
            },
        ],
        [
            '@babel/preset-react',
            {
                development: isDev,
                useBuiltIns: true,
                runtime: 'automatic',
            },
        ],
        '@babel/typescript',
    ],
    plugins: ['./my-plugin.js'],
    env: {
        production: {
            ignore: ['**/*.test.tsx', '**/*.test.ts', '__snapshots__', '__tests__'],
        },
        development: {
            ignore: ['**/*.test.tsx', '**/*.test.ts', '__snapshots__', '__tests__'],
        },
        test: {
            ignore: ['__snapshots__'],
        },
    },
};

Environment

System:
    OS: Windows 10 10.0.19042
  Binaries:
    Node: 15.0.1 - C:\Program Files\nodejs\node.EXE        
    Yarn: 1.22.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 7.0.3 - C:\Program Files\nodejs\npm.CMD
  npmPackages:
    @babel/cli: ^7.12.8 => 7.12.8 
    @babel/core: ^7.12.9 => 7.12.9 
    @babel/helper-plugin-utils: ^7.10.4 => 7.10.4 
    @babel/plugin-syntax-jsx: ^7.12.1 => 7.12.1 
    @babel/preset-env: ^7.12.7 => 7.12.7 
    @babel/preset-react: ^7.12.7 => 7.12.7 
    @babel/preset-typescript: ^7.12.7 => 7.12.7 
    babel-jest: ^26.6.3 => 26.6.3 
    babel-loader: ^8.2.2 => 8.2.2 
    jest: ^26.6.3 => 26.6.3 
    webpack: ^5.10.0 => 5.10.0 

Additional context

Here is the repo. Use next branch

@babel-bot
Copy link
Collaborator

Hey @budarin! We really appreciate you taking the time to report an issue. The collaborators on this project attempt to help as many people as possible, but we're a limited number of volunteers, so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack community that typically always has someone willing to help. You can sign-up here for an invite."

@JLHwung
Copy link
Contributor

JLHwung commented Dec 9, 2020

require("babel-plugin-syntax-jsx"),

babel-plugin-syntax-jsx is for Babel 6, you should inherit @babel/plugin-syntax-jsx instead.

@budarin
Copy link
Author

budarin commented Dec 9, 2020

require("babel-plugin-syntax-jsx"),

babel-plugin-syntax-jsx is for Babel 6, you should inherit @babel/plugin-syntax-jsx instead.

Thanks!

@budarin budarin closed this as completed Dec 9, 2020
@budarin
Copy link
Author

budarin commented Dec 9, 2020

I'm sorry, but it did not help

I added @babel/plugin-syntax-jsx to package.json and installed it into node_modules, replaced babel-plugin-syntax-jsx with it, but the error is still here :(

@budarin budarin reopened this Dec 9, 2020
@budarin
Copy link
Author

budarin commented Dec 11, 2020

have added

const core = require('@babel/core');
const t = require('@babel/types');
const template = require('@babel/template');
const jsx = require('@babel/plugin-syntax-jsx').default;

module.exports = () => ({
    name: 'my-plugin',
    inherits: jsx,
    manipulateOptions: (opts, parserOpts) => {
        console.log('manipulateOptions'.toUpperCase(), parserOpts);
    },
   ...

have log

MANIPULATEOPTIONS {
  sourceType: 'module',
  sourceFileName: '.../projects/my-component/babel-plugin/my-plugin.js',
  plugins: [ 'jsx' ]
}

jsx plugin is in plugins option
but the error still here

SyntaxError: This experimental syntax requires enabling one of the following parser plugin(s): 'jsx, flow, typescript' (2:30)
      1 | (
    > 2 | ({children, ...rest}) => <Component {...rest}>{children}</Component>;
        |                          ^
      3 | )

@nicolo-ribaudo
Copy link
Member

What is the name of the file containing ({children, ...rest}) => <Component {...rest}>{children}</Component>;?

@budarin
Copy link
Author

budarin commented Dec 11, 2020

@nicolo-ribaudo
babel-plugin/bubel-plugin-bem-button.js in next brach

@nicolo-ribaudo
Copy link
Member

nicolo-ribaudo commented Dec 11, 2020

You need to create one of the templates in the plugin like this, to enable JSX in that template:

const getResult = template.expression({ plugins: ['jsx'] })`
    ({children, ...restProps}) => <Component {...restProps} PARAMS>{children}</Component>
`;

Also, you need to inherit from require('@babel/plugin-syntax-jsx').default.

Then there is an error about PARAMS being undefined, but it's probably caused by some wrong logic somewhere else (I'm not sure about how to solve it, but you could just remove PARAMS from the template and manually add them to the AST returned by getResult).

@budarin
Copy link
Author

budarin commented Dec 11, 2020

@nicolo-ribaudo

thanks a lot!

@budarin budarin closed this as completed Dec 11, 2020
@budarin
Copy link
Author

budarin commented Dec 12, 2020

@nicolo-ribaudo

I have rewritten the plugin with babel/types
test is green but a new strange error is raised:

ERROR in ./src/components/button2.tsx 7:6
Module parse failed: Unexpected token (7:6)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|   children: children,
|   ...rest
> }) => <Component {...rest} size="l" view="action" width="max">{children}</Component>;
 @ ./src/index.tsx 14:0-47 24:36-43

I can't understand what this error is about - babel/preset-env, babel/react and babel/typescript are in babel config and babel-loader is in webpack config...

plugin generates right code:

import { Button, withSizeM, withViewAction, withWidthMax } from '@yandex/ui/Button/desktop';
import { compose } from '@bem-react/core';
const Component = compose(withSizeM, withViewAction, withWidthMax)(Button);
export const Button2 = ({ children: children, ...rest }) => (
    <Component {...rest} size="m" view="action" width="max">
        {children}
    </Component>
);

here is transform result with babel-cli:

import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
var _jsxFileName = ".../projects/bem-like-component/babel-plugin/__tests__/__fixtures__/output.js";
import { Button, withSizeM, withViewAction, withWidthMax } from '@yandex/ui/Button/desktop';
import { compose } from '@bem-react/core';
const Component = compose(withSizeM, withViewAction, withWidthMax)(Button);
export const Button2 = ({
  children: children,
  ...rest
}) => /*#__PURE__*/_jsxDEV(Component, { ...rest,
  size: "m",
  view: "action",
  width: "max",
  children: children
}, void 0, false, {
  fileName: _jsxFileName,
  lineNumber: 5,
  columnNumber: 5
}, this);

I don't understand what I should to do with this and this error

please, have a look at next branch

@nicolo-ribaudo
Copy link
Member

If you add console.log(result.body);, you'll notice that you are getting this:

{
  type: 'Identifier',
  name: '<Component {...restProps} size="l" view="action" width="max">{children}</Component>'
}

You need to pass an AST node to getResult (you can manually build it with @babel/types), not a string.

@budarin
Copy link
Author

budarin commented Dec 18, 2020

@nicolo-ribaudo

I've rewritten code with @babel/types
Test is green
console.log(result.body);:

{
  type: 'JSXElement',
  openingElement: {
    type: 'JSXOpeningElement',
    name: { type: 'JSXIdentifier', name: 'Component' },
    attributes: [ [Object], [Object], [Object], [Object] ],
    selfClosing: false
  },
  closingElement: {
    type: 'JSXClosingElement',
    name: { type: 'JSXIdentifier', name: 'Component' }
  },
  children: [ { type: 'JSXExpressionContainer', expression: [Object] } ],
  selfClosing: null
}

but still have the error in browser:

Uncaught Error: Module parse failed: Unexpected token (7:6)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|   children: children,
|   ...rest
> }) => <Component {...rest} size="l" view="action" width="max">{children}</Component>;
    at Object../src/components/button2.tsx (client.js:1518)

@nicolo-ribaudo
Copy link
Member

Oh you also need to delete path.skip();, since that's telling Babel "please don't further transform these AST nodes". Btw, you can probably reduce @babel/types usage like this:

const result = getResult({
  JSX: t.jsxElement(
    t.jsxOpeningElement(t.jsxIdentifier("Component"), attributes),
    t.jsxClosingElement(t.jsxIdentifier("Component")),
    [t.jsxExpressionContainer(t.identifier("children"))]
  ),
});

@budarin
Copy link
Author

budarin commented Dec 18, 2020

thanks for the reply and reduced code

I've commented path.skip(); - here is another error :(

client.js:1518 Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js):
TypeError: /projects/bem-like-component/src/components/button2.tsx: pass.get(...) is not a function
    at Object.post (/projects/bem-like-component/node_modules/@babel/plugin-transform-react-jsx-development/lib/index.js:37)
    at buildJSXElementCall (/projects/bem-like-component/node_modules/@babel/plugin-transform-react-jsx-development/node_modules/@babel/helper-builder-react-jsx-experimental/lib/index.js:481)
    at PluginPass.exit (/projects/bem-like-component/node_modules/@babel/plugin-transform-react-jsx-development/node_modules/@babel/helper-builder-react-jsx-experimental/lib/index.js:80)
    at newFn (/projects/bem-like-component/node_modules/@babel/core/node_modules/@babel/traverse/lib/visitors.js:175)
    at NodePath._call (projects/bem-like-component/node_modules/@babel/core/node_modules/@babel/traverse/lib/path/context.js:55)
    at NodePath.call (/projects/bem-like-component/node_modules/@babel/core/node_modules/@babel/traverse/lib/path/context.js:42)
    at NodePath.visit (/projects/bem-like-component/node_modules/@babel/core/node_modules/@babel/traverse/lib/path/context.js:101)
    at TraversalContext.visitQueue (/projects/bem-like-component/node_modules/@babel/core/node_modules/@babel/traverse/lib/context.js:115)
    at TraversalContext.visitSingle (/projects/bem-like-component/node_modules/@babel/core/node_modules/@babel/traverse/lib/context.js:84)
    at TraversalContext.visit (/projects/bem-like-component/node_modules/@babel/core/node_modules/@babel/traverse/lib/context.js:143)
    at Object../src/components/button2.tsx (client.js:1518)

@JLHwung
Copy link
Contributor

JLHwung commented Dec 18, 2020

I believe it has been fixed in #12479, please update @babel/* to latest (v7.12.11).

@budarin
Copy link
Author

budarin commented Dec 18, 2020

I believe it has been fixed in #12479, please update @babel/* to latest (v7.12.11).

I try to install packages with v7.12.11 version but yarn offers me to select the latest only v7.12.10

@nicolo-ribaudo
Copy link
Member

I'm not getting errors anymore in your repository 🤔
Schermata da 2020-12-19 00-56-29

@budarin
Copy link
Author

budarin commented Dec 19, 2020

it might be incorrect cache!
Thanks! it works!

@budarin budarin closed this as completed Dec 19, 2020
@github-actions github-actions bot added the outdated A closed issue/PR that is archived due to age. Recommended to make a new issue label Mar 20, 2021
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 20, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
i: question outdated A closed issue/PR that is archived due to age. Recommended to make a new issue
Projects
None yet
Development

No branches or pull requests

4 participants