汇总 + @babel/preset-env + @babel/polyfill

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

在使用 Rollup 时,如何让它与 @babel/preset-env@babel/polyfill 一起工作?文档提到要添加 useBuiltIns: 'usage' 但是当我这样做时,我在控制台中收到 require is not defined 错误。以下是我目前所拥有的;有没有更推荐的设置?

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
        }
      }
    ]
  ]
}

我通过删除我的 .babelrc 文件并将我的 babel 配置完全移动到 rollup.config.js 来解决这个问题。然后我还包含了 rollup-plugin-commonjs 插件来将 CJS 模块转换为 ES6。我的最终配置示例:

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()
  ]
};

完整配置 here。当然仍然欢迎提出改进建议。