javascriptbabeljsrollupbabel-polyfillbabel-preset-env

Rollup + @babel/preset-env + @babel/polyfill


When using Rollup how can you get it to work with both @babel/preset-env and @babel/polyfill? The docs mentioned to add useBuiltIns: 'usage' but when I do this I get a require is not defined error in console. Below is what I have so far; is there a more recommended setup?

rollup.config.js:

import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';

const dist = './dist/';
const name = 'focusoverlay';

export default {
  input: './src/index.js',
  output: [
    {
      file: `${dist}${name}.cjs.js`,
      format: 'cjs'
    },
    {
      file: `${dist}${name}.esm.js`,
      format: 'esm'
    },
    {
      name: 'FocusOverlay',
      file: `${dist}${name}.js`,
      format: 'umd'
    }
  ],
  plugins: [
      resolve(),
      babel({ exclude: 'node_modules/**' }),
      terser()
  ]
};

.babelrc:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage",
        "modules": false,
        "targets": {
          "browsers": "> 0.25%, not op_mini all, not dead, IE 10-11",
          "node": 6
        }
      }
    ]
  ]
}

Solution

  • I fixed this by removing my .babelrc file and moving my babel configuration entirely to rollup.config.js. Then I also included the rollup-plugin-commonjs plugin to convert CJS modules to ES6. Example of my final config:

    import babel from 'rollup-plugin-babel';
    import resolve from 'rollup-plugin-node-resolve';
    import commonjs from 'rollup-plugin-commonjs';
    import { terser } from 'rollup-plugin-terser';
    
    const dist = './dist/';
    const name = 'focusoverlay';
    
    export default {
      input: './src/index.js',
      output: [
        {
          file: `${dist}${name}.cjs.js`,
          format: 'cjs'
        },
        {
          file: `${dist}${name}.esm.js`,
          format: 'esm'
        },
        {
          name: 'FocusOverlay',
          file: `${dist}${name}.js`,
          format: 'umd'
        }
      ],
      plugins: [
          resolve(),
          babel({
            exclude: 'node_modules/**',
            presets: [
              [
                '@babel/env',
                {
                  modules: 'false',
                  targets: {
                    browsers: '> 1%, IE 11, not op_mini all, not dead',
                    node: 8
                  },
                  useBuiltIns: 'usage'
                }
              ]
            ]
          }),
          commonjs(),
          terser()
      ]
    };
    

    Full config here. Suggestions for improvement of course still welcome.