包详细信息

rollup-plugin-babel

rollup2.9mMIT不推荐使用4.4.0

This package has been deprecated and is no longer maintained. Please use @rollup/plugin-babel.

Seamless integration between Rollup and Babel.

rollup-plugin, babel, es2015, es6

自述文件

rollup-plugin-babel

Seamless integration between Rollup and Babel.

Why?

If you're using Babel to transpile your ES6/7 code and Rollup to generate a standalone bundle, you have a couple of options:

  • run the code through Babel first, being careful to exclude the module transformer, or
  • run the code through Rollup first, and then pass it to Babel.

Both approaches have disadvantages – in the first case, on top of the additional configuration complexity, you may end up with Babel's helpers (like classCallCheck) repeated throughout your code (once for each module where the helpers are used). In the second case, transpiling is likely to be slower, because transpiling a large bundle is much more work for Babel than transpiling a set of small files.

Either way, you have to worry about a place to put the intermediate files, and getting sourcemaps to behave becomes a royal pain.

Using Rollup with rollup-plugin-babel makes the process far easier.

Installation

babel 7.x

npm install --save-dev rollup-plugin-babel@latest

babel 6.x

npm install --save-dev rollup-plugin-babel@3

Usage

import { rollup } from 'rollup';
import babel from 'rollup-plugin-babel';

rollup({
  entry: 'main.js',
  plugins: [
    babel({
      exclude: 'node_modules/**'
    })
  ]
}).then(...)

All options are as per the Babel documentation, plus the following:

  • options.externalHelpers: a boolean value indicating whether to bundle in the Babel helpers
  • options.include and options.exclude: each a minimatch pattern, or array of minimatch patterns, which determine which files are transpiled by Babel (by default, all files are transpiled)
  • options.externalHelpersWhitelist: an array which gives explicit control over which babelHelper functions are allowed in the bundle (by default, every helper is allowed)
  • options.extensions: an array of file extensions that Babel should transpile (by default the Babel defaults of .js, .jsx, .es6, .es, .mjs. are used)

Babel will respect .babelrc files – this is generally the best place to put your configuration.

External dependencies

Ideally, you should only be transforming your source code, rather than running all of your external dependencies through Babel – hence the exclude: 'node_modules/**' in the example above. If you have a dependency that exposes untranspiled ES6 source code that doesn't run in your target environment, then you may need to break this rule, but it often causes problems with unusual .babelrc files or mismatched versions of Babel.

We encourage library authors not to distribute code that uses untranspiled ES6 features (other than modules) for this reason. Consumers of your library should not have to transpile your ES6 code, any more than they should have to transpile your CoffeeScript, ClojureScript or TypeScript.

Use babelrc: false to prevent Babel from using local (i.e. to your external dependencies) .babelrc files, relying instead on the configuration you pass in.

Helpers

In some cases Babel uses helpers to avoid repeating chunks of code – for example, if you use the class keyword, it will use a classCallCheck function to ensure that the class is instantiated correctly.

By default, those helpers will be inserted at the top of the file being transformed, which can lead to duplication. This rollup plugin automatically deduplicates those helpers, keeping only one copy of each one used in the output bundle. Rollup will combine the helpers in a single block at the top of your bundle. To achieve the same in Babel 6 you must use the external-helpers plugin.

Alternatively, if you know what you're doing, you can use the transform-runtime plugin. If you do this, use runtimeHelpers: true:

rollup.rollup({
  ...,
  plugins: [
    babel({ runtimeHelpers: true })
  ]
}).then(...)

By default externalHelpers option is set to false so babel helpers will be included in your bundle.

If you do not wish the babel helpers to be included in your bundle at all (but instead reference the global babelHelpers object), you may set the externalHelpers option to true:

rollup.rollup({
  ...,
  plugins: [
    babel({
      plugins: ['external-helpers'],
      externalHelpers: true
    })
  ]
}).then(...)

Modules

This is not needed for Babel 7 - it knows automatically that Rollup understands ES modules & that it shouldn't use any module transform with it. The section below describes what needs to be done for Babel 6.

The env preset includes the transform-es2015-modules-commonjs plugin, which converts ES6 modules to CommonJS – preventing Rollup from working. Since Babel 6.3 it's possible to deactivate module transformation with "modules": false. So there is no need to use the old workaround with babel-preset-es2015-rollup, that will work for Babel <6.13. Rollup will throw an error if this is incorrectly configured.

However, setting modules: false in your .babelrc may conflict if you are using babel-register. To work around this, specify babelrc: false in your rollup config. This allows Rollup to bypass your .babelrc file. In order to use the env preset, you will also need to specify it with modules: false option:

plugins: [
    babel({
        babelrc: false,
        presets: [['env', { modules: false }]],
    }),
];

Configuring Babel 6

The following applies to Babel 6 only. If you're using Babel 5, do npm i -D rollup-plugin-babel@1, as version 2 and above no longer supports Babel 5

npm install --save-dev rollup-plugin-babel@3 babel-preset-env babel-plugin-external-helpers
// .babelrc
{
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ]
  ],
  "plugins": [
    "external-helpers"
  ]
}

Custom plugin builder

rollup-plugin-babel exposes a plugin-builder utility that allows users to add custom handling of Babel's configuration for each file that it processes.

.custom accepts a callback that will be called with the loader's instance of babel so that tooling can ensure that it using exactly the same @babel/core instance as the loader itself.

It's main purpose is to allow other tools for configuration of transpilation without forcing people to add extra configuration but still allow for using their own babelrc / babel config files.

Example

import babel from 'rollup-plugin-babel';

export default babel.custom(babelCore => {
    function myPlugin() {
        return {
            visitor: {},
        };
    }

    return {
        // Passed the plugin options.
        options({ opt1, opt2, ...pluginOptions }) {
            return {
                // Pull out any custom options that the plugin might have.
                customOptions: { opt1, opt2 },

                // Pass the options back with the two custom options removed.
                pluginOptions,
            };
        },

        config(cfg /* Passed Babel's 'PartialConfig' object. */, { code, customOptions }) {
            if (cfg.hasFilesystemConfig()) {
                // Use the normal config
                return cfg.options;
            }

            return {
                ...cfg.options,
                plugins: [
                    ...(cfg.options.plugins || []),

                    // Include a custom plugin in the options.
                    myPlugin,
                ],
            };
        },

        result(result, { code, customOptions, config, transformOptions }) {
            return {
                ...result,
                code: result.code + '\n// Generated by some custom plugin',
            };
        },
    };
});

License

MIT

更新日志

4.3.2

  • Fixed usage with externalHelpers: true option

4.3.1

  • Add .js extension to the virtual babel helpers file (only matters when using preserveModules option in rollup)

4.3.0

  • Added .custom builder.
  • Fail build when a plugin tries to add non existent babel helper

4.2.0

Allow rollup@1 as peer dependency.

4.1.0

  • Fixed "preflight check" for ignored files.
  • Return null when no transformation has been done (fixing source maps for this case)

4.0.3

Fixed fallback class transform in "preflight check".

4.0.2

Fixed rollup peer dependency.

4.0.0

Babel 7 compatible! (dropped Babel 6 compatibility though).

Additionally:

  • Internal preflight checks are created now per plugin instance, so using 2 instances of rollup-plugin-babel (i.e. targeting 2 different set of files with include/exclude options) shouldn't conflict with each other
  • Transpiling by default only what Babel transpiles - files with those extensions: .js, .jsx, .es6, .es, .mjs. You can customize this with new extensions option. This also fixes long standing issue with rollup-plugin-babel trying to transform JSON files.

3.0.3

  • Drop babel7 support. Use 4.0.0-beta if you use babel 7
  • Use "module" in addition to "jsnext:main" (#150)
  • Remove unused babel helpers namespace declaration & expression (#164)

3.0.2

  • Fix regression with Babel 6 (#158)

3.0.1

  • Wasn't working, fix bug with transform (not using es2015-classes for preflight check)

3.0.0

  • Drop Node 0.10/0.12 (Use native Object.assign)
  • Change babel-core to be a peerDependency
  • Support babel-core v7 as well as a peerDep (no changes necessary)

2.7.1

  • Prevent erroneous warnings about duplicated runtime helpers (#105)
  • Ignore ignore option in preflight check (#102)
  • Allow custom moduleName with runtime-helpers (#95)

2.7.0

  • Add externalHelpersWhitelist option (#92)
  • Ignore only option during preflight checks (#98)
  • Use options.onwarn if available (#84)
  • Update documentation and dependencies

2.6.1

  • Return a name

2.6.0

  • Use \0 convention for helper module ID (#64)

2.5.1

  • Don't mutate options.plugins (#47)

2.5.0

  • Import babelHelpers rather than injecting them – allows transform function to be pure (#rollup/658)

2.4.0

  • Add externalHelpers option (#41)

2.3.9

  • Do not rename Babel helpers (#34)

2.3.8

  • Create new version to (hopefully) solve bizarre CI issue

2.3.7

  • Be less clever about renaming Babel helpers (#19)

2.3.6

  • Fix cache misses in preflight check (#29)

2.3.5

  • Use class transformer local to plugin, not project being built

2.3.4

  • Ensure class transformer is present for preflight check, and only run check once per directory (#23)

2.3.3

  • Fix helper renaming (#22)

2.3.1-2

  • Include correct files in npm package

2.3.0

  • Allow transform-runtime Babel plugin, if combined with runtimeHelpers: true option (#17)
  • More permissive handling of helpers – only warn if inline helpers are duplicated
  • Handle plugins that change export patterns (#18)

2.2.0

  • Preflight checks are run per-file, to avoid configuration snafus (#16)

2.1.0

  • Generate sourcemaps by default

2.0.1

  • Use object-assign ponyfill
  • Add travis support
  • Fix test

2.0.0

  • Babel 6 compatible

1.0.0

  • First release