babel/babel-loader


📦 Babel loader for webpack

License: MIT

Language: JavaScript

Keywords: babel, loader, webpack


This README is for babel-loader v8 + Babel v7 Check the 7.x branch for docs with Babel v6

NPM Status Build Status Build Status codecov

Babel Loader

This package allows transpiling JavaScript files using Babel and webpack.

Note: Issues with the output should be reported on the Babel Issues tracker.

Install

webpack 4.x | babel-loader 8.x | babel 7.x

npm install -D babel-loader @babel/core @babel/preset-env webpack

Usage

webpack documentation: Loaders

Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:

module: {
  rules: [
    {
      test: /\.m?js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    }
  ]
}

Options

See the babel options.

You can pass options to the loader by using the options property:

module: {
  rules: [
    {
      test: /\.m?js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env'],
          plugins: ['@babel/plugin-proposal-object-rest-spread']
        }
      }
    }
  ]
}

This loader also supports the following loader-specific option:

  • cacheDirectory: Default false. When set, the given directory will be used to cache the results of the loader. Future webpack builds will attempt to read from the cache to avoid needing to run the potentially expensive Babel recompilation process on each run. If the value is blank (loader: 'babel-loader?cacheDirectory') or true (loader: 'babel-loader?cacheDirectory=true'), the loader will use the default cache directory in node_modules/.cache/babel-loader or fallback to the default OS temporary file directory if no node_modules folder could be found in any root directory.

  • cacheIdentifier: Default is a string composed by the @babel/core's version, the babel-loader's version, the contents of .babelrc file if it exists, and the value of the environment variable BABEL_ENV with a fallback to the NODE_ENV environment variable. This can be set to a custom value to force cache busting if the identifier changes.

  • cacheCompression: Default true. When set, each Babel transform output will be compressed with Gzip. If you want to opt-out of cache compression, set it to false -- your project may benefit from this if it transpiles thousands of files.

  • customize: Default null. The path of a module that exports a custom callback like the one that you'd pass to .custom(). Since you already have to make a new file to use this, it is recommended that you instead use .custom to create a wrapper loader. Only use this is you must continue using babel-loader directly, but still want to customize.

Troubleshooting

babel-loader is slow!

Make sure you are transforming as few files as possible. Because you are probably matching /\.m?js$/, you might be transforming the node_modules folder or other unwanted source.

To exclude node_modules, see the exclude option in the loaders config as documented above.

You can also speed up babel-loader by as much as 2x by using the cacheDirectory option. This will cache transformations to the filesystem.

Babel is injecting helpers into each file and bloating my code!

Babel uses very small helpers for common functions such as _extend. By default, this will be added to every file that requires it.

You can instead require the Babel runtime as a separate module to avoid the duplication.

The following configuration disables automatic per-file runtime injection in Babel, requiring @babel/plugin-transform-runtime instead and making all helper references use it.

See the docs for more information.

NOTE: You must run npm install -D @babel/plugin-transform-runtime to include this in your project and @babel/runtime itself as a dependency with npm install @babel/runtime.

rules: [
  // the 'transform-runtime' plugin tells Babel to
  // require the runtime instead of inlining it.
  {
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env'],
        plugins: ['@babel/plugin-transform-runtime']
      }
    }
  }
]

NOTE: transform-runtime & custom polyfills (e.g. Promise library)

Since @babel/plugin-transform-runtime includes a polyfill that includes a custom regenerator-runtime and core-js, the following usual shimming method using webpack.ProvidePlugin will not work:

// ...
        new webpack.ProvidePlugin({
            'Promise': 'bluebird'
        }),
// ...

The following approach will not work either:

require('@babel/runtime/core-js/promise').default = require('bluebird');

var promise = new Promise;

which outputs to (using runtime):

'use strict';

var _Promise = require('@babel/runtime/core-js/promise')['default'];

require('@babel/runtime/core-js/promise')['default'] = require('bluebird');

var promise = new _Promise();

The previous Promise library is referenced and used before it is overridden.

One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:

// bootstrap.js

require('@babel/runtime/core-js/promise').default = require('bluebird');

// ...

require('./app');

The Node.js API for babel has been moved to babel-core.

If you receive this message, it means that you have the npm package babel installed and are using the short notation of the loader in the webpack config (which is not valid anymore as of webpack 2.x):

  {
    test: /\.m?js$/,
    loader: 'babel',
  }

webpack then tries to load the babel package instead of the babel-loader.

To fix this, you should uninstall the npm package babel, as it is deprecated in Babel v6. (Instead, install @babel/cli or @babel/core.) In the case one of your dependencies is installing babel and you cannot uninstall it yourself, use the complete name of the loader in the webpack config:

  {
    test: /\.m?js$/,
    loader: 'babel-loader',
  }

Customized Loader

babel-loader exposes a loader-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.

In cases where you want to customize without actually having a file to call .custom, you may also pass the customize option with a string pointing at a file that exports your custom callback function.

Example

// Export from "./my-custom-loader.js" or whatever you want.
module.exports = require("babel-loader").custom(babel => {
  function myPlugin() {
    return {
      visitor: {},
    };
  }

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

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

    // Passed Babel's 'PartialConfig' object.
    config(cfg) {
      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) {
      return {
        ...result,
        code: result.code + "\n// Generated by some custom loader",
      };
    },
  };
});
// And in your Webpack config
module.exports = {
  // ..
  module: {
    rules: [{
      // ...
      loader: path.join(__dirname, 'my-custom-loader.js'),
      // ...
    }]
  }
};

customOptions(options: Object): { custom: Object, loader: Object }

Given the loader's options, split custom options out of babel-loader's options.

config(cfg: PartialConfig): Object

Given Babel's PartialConfig object, return the options object that should be passed to babel.transform.

result(result: Result): Result

Given Babel's result object, allow loaders to make additional tweaks to it.

License

MIT

Project Statistics

Sourcerank 24
Repository Size 1.08 MB
Stars 3,669
Forks 322
Watchers 69
Open issues 35
Dependencies 856
Contributors 95
Tags 66
Created
Last updated
Last pushed

Top Contributors See all

Luís Couto Logan Smyth greenkeeper[bot] Sebastian Henry Zhu Michael Ciniawsky Shinnosuke Watanabe jupl Joe Lencioni Samuel Reed Sven Sauleau Joshua Wiens Jason Quense Iurii Kucherov Hawken Rives Andy Edwards Ryunosuke Sato Nicholas Kinsey Dan Abramov Brian Ng

Packages Referencing this Repo

@gerhobbelt/babel-loader
babel module loader for webpack
Latest release 8.0.0-2 - Updated - 3.67K stars
6to5-loader
6t05 module loader for webpack
Latest release 3.0.0 - Updated - 3.67K stars
heroku-babel-loader
babel module loader for webpack with caching fixed to work on Heroku
Latest release 8.0.4 - Updated - 3.67K stars
@ream/babel-loader
babel module loader for webpack
Latest release 7.0.0 - Published - 3.67K stars
babel-fast-react-loader
babel fast react module loader for webpack
Latest release 5.3.3 - Updated - 3.67K stars
af-babel-loader
babel module loader for webpack
Latest release 7.1.3 - Updated - 3.67K stars
fis-msprd-babel-loader_6_2_10
babel module loader for webpack
Latest release 6.2.10 - Published - 3.67K stars
@egoistian/babel-loader
babel module loader for webpack
Latest release 7.0.0 - Published - 3.67K stars
org.webjars.npm:babel-loader
WebJar for babel-loader
Latest release 6.2.4 - Updated - 3.67K stars
loose-babel-loader
babel module loader for webpack
Latest release 6.2.2 - Published - 3.67K stars
isv-ali-babel-loader
babel module loader for webpack
Latest release 10.0.9 - Updated - 3.67K stars
babel5-loader
babel module loader for webpack
Latest release 5.3.3 - Published - 3.67K stars
babel-loader
babel module loader for webpack
Latest release 8.0.5 - Updated - 3.67K stars

Recent Tags See all

v8.0.5 January 04, 2019
v8.0.4 September 27, 2018
v8.0.3 September 27, 2018
v8.0.2 September 03, 2018
v8.0.1 September 01, 2018
v8.0.0 August 27, 2018
v8.0.0-beta.6 August 21, 2018
v7.1.5 July 05, 2018
v8.0.0-beta.4 June 22, 2018
v8.0.0-beta.3 May 17, 2018
v7.1.4 March 06, 2018
v8.0.0-beta.2 February 26, 2018
v8.0.0-beta.1 February 25, 2018
v7.1.3 February 25, 2018
v8.0.0-beta.0 October 31, 2017

Interesting Forks See all

hantq/babel-loader
Webpack plugin for Babel
JavaScript - Last pushed - 1 stars
yyx990803/babel-loader
Webpack plugin for Babel
JavaScript - Last pushed - 1 stars - 1 forks
superposition/babel-loader
📦 Webpack plugin for Babel
JavaScript - Published - 1 stars

Something wrong with this page? Make a suggestion

Last synced: 2019-04-20 05:20:57 UTC

Login to resync this repository