22

I'm trying to use Rollup + React but I'm encounting an error when rollup encounters JSX.

Unexpected token... export default () => <p>M...

I have a repo that triggers the error. All documentation/examples I've found using Rollup + React don't use the latest Babel so it might have something to do with Babel.

rollup.config.js:

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import pkg from './package.json';

export default [{
        input: 'src/index.js',
        output: {
        name: 'index',
        file: pkg.main,
        format: 'umd'
    },
    plugins: [
        resolve(),
        commonjs(),
        babel({ 
            exclude: 'node_modules/**',
            presets: ['@babel/env', '@babel/preset-react']
        })
    ],
    external: [
        'react',
        'prop-types',
    ],
    globals: {
        react: "React"
    }
},
];

.babelrc:

{
  "presets": [
  ["@babel/env", { "modules": false }], "@babel/preset-react"]
}
Brad Woods
  • 1,507
  • 2
  • 12
  • 30

2 Answers2

24

The solution to this is two swap the order of 2 of the plugins

from:

plugins: [
    resolve(),
    commonjs(),
    babel({ 
        exclude: 'node_modules/**',
        presets: ['@babel/env', '@babel/preset-react']
    })
],

to:

plugins: [
    resolve(),
    babel({ 
        exclude: 'node_modules/**',
        presets: ['@babel/env', '@babel/preset-react']
    }),
    commonjs()
],

Thanks vladshcherbin.

Brad Woods
  • 1,507
  • 2
  • 12
  • 30
  • 4
    From the npm site: https://www.npmjs.com/package/@rollup/plugin-babel Using With `@rollup/plugin-commonjs` When using `@rollup/plugin-babel` with `@rollup/plugin-commonjs` in the same Rollup configuration, it's important to note that `@rollup/plugin-commonjs` must be placed before this plugin in the plugins array for the two to work together properly – Josh Dando Feb 10 '21 at 14:18
  • 1
    I can only imagine the pain you'd have gone through to find this out. GG. – nikamanish Dec 19 '21 at 06:40
2

To anyone coming across this issue, it is recommended to place commonjs before babel according to the documentation. The issue can be solved by adding the following instead commonjs({ include: /node_modules/ }).

This gives a good explanation as to why https://github.com/rollup/plugins/issues/805#issuecomment-779902868