Socket
Socket
Sign inDemoInstall

babel-loader

Package Overview
Dependencies
315
Maintainers
2
Versions
77
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    babel-loader

babel module loader for webpack


Version published
Maintainers
2
Install size
265 kB
Created

Package description

What is babel-loader?

The babel-loader npm package is a Webpack plugin that integrates Babel with Webpack. Babel is a JavaScript compiler that allows you to use next-generation JavaScript, today. It compiles ES6 and beyond into ES5 code that can run in current browser environments. babel-loader enables Webpack to process and bundle JavaScript files using Babel.

What are babel-loader's main functionalities?

Transpiling ES6+ to ES5

This feature allows developers to write modern JavaScript code without worrying about compatibility issues with older browsers. The code sample shows a Webpack configuration that uses babel-loader to process files ending in .js, excluding node_modules, and transpiles them using the preset '@babel/preset-env'.

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
};

Using Babel plugins

babel-loader can be configured to use specific Babel plugins to enable experimental features or custom transformations. The code sample demonstrates how to include the '@babel/plugin-proposal-class-properties' plugin to allow the use of class properties syntax in JavaScript.

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            plugins: ['@babel/plugin-proposal-class-properties']
          }
        }
      }
    ]
  }
};

Source Maps support

babel-loader supports source maps, which help in debugging transpiled code by mapping the transformed code back to the original source code. The code sample shows how to enable source maps in the babel-loader options.

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            sourceMaps: true
          }
        }
      }
    ]
  }
};

Other packages similar to babel-loader

Changelog

Source

v6.2.7

😢 Regression

Fallback to os.tmpdir() if no cachedir found (#318) (fixes #317) @danez

Fixes an issue with v6.2.6 when using babel-loader as a global package.

Readme

Source

babel-loader NPM Status Build Status codecov

Babel is a compiler for writing next generation JavaScript.

This package allows transpiling JavaScript files using Babel and webpack.

Notes: Issues with the output should be reported on the babel issue tracker;

Installation

npm install babel-loader babel-core babel-preset-es2015 --save-dev

Note: npm deprecated auto-installing of peerDependencies since npm@3, so required peer dependencies like babel-core and webpack must be listed explicitly in your package.json.

Note: If you're upgrading from babel 5 to babel 6, please take a look at this guide.

Usage

Documentation: Using loaders

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

module: {
loaders: [
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    loader: 'babel', // 'babel-loader' is also a valid name to reference
    query: {
      presets: ['es2015']
    }
  }
]
}

Options

See the babel options.

You can pass options to the loader by writing them as a query string:

module: {
loaders: [
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    loader: 'babel?presets[]=es2015'
  }
]
}

or by using the query property:

module: {
loaders: [
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    loader: 'babel',
    query: {
      presets: ['es2015']
    }
  }
]
}

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') the loader will use the default cache directory in node_modules/.cache/babel-loader.

  • 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.

Note: The sourceMap option is ignored, instead sourceMaps are automatically enabled when webpack is configured to use them (via the devtool config option).

Troubleshooting

babel-loader is slow!

Make sure you are transforming as few files as possible. Because you are probably matching /\.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, instead requiring babel-plugin-transform-runtime and making all helper references use it.

See the docs for more information.

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

loaders: [
  // the 'transform-runtime' plugin tells babel to require the runtime
  // instead of inlining it.
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    loader: 'babel',
    query: {
      presets: ['es2015'],
      plugins: ['transform-runtime']
    }
  }
]

The node 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 use the short notation of the loader in the webpack config:

  {
    test: /\.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: /\.js$/,
    loader: 'babel-loader',
  }

using cacheDirectory fails with ENOENT Error

If using cacheDirectory results in an error similar to the following:

ERROR in ./frontend/src/main.js
Module build failed: Error: ENOENT, open 'true/350c59cae6b7bce3bb58c8240147581bfdc9cccc.json.gzip'
 @ multi app

(notice the true/ in the filepath)

That means that most likely, you're not setting the options correctly, and you're doing something similar to:

loaders: [
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    loader: 'babel?cacheDirectory=true'
  }
]

That's not the correct way of setting boolean values. You should do instead:

loaders: [
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    loader: 'babel?cacheDirectory'
  }
]

or use the query property:

loaders: [
  // the optional 'runtime' transformer tells babel to require the runtime
  // instead of inlining it.
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    loader: 'babel',
    query: {
      cacheDirectory: true
    }
  }
]

custom polyfills (e.g. Promise library)

Since Babel 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');

License

Keywords

FAQs

Last updated on 27 Oct 2016

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc