• Stars
    star
    4,794
  • Rank 8,336 (Top 0.2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

đŸ“Ļ Babel loader for webpack

This README is for babel-loader v8/v9 with Babel v7 If you are using legacy Babel v6, see the 7.x branch docs

NPM 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

babel-loader supported webpack versions supported Babel versions supported Node.js versions
8.x 4.x or 5.x 7.x >= 8.9
9.x 5.x ^7.12.0 >= 14.15.0
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: /\.(?:js|mjs|cjs)$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env', { targets: "defaults" }]
          ]
        }
      }
    }
  ]
}

Options

See the babel options.

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

module: {
  rules: [
    {
      test: /\.(?:js|mjs|cjs)$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env', { targets: "defaults" }]
          ],
          plugins: ['@babel/plugin-proposal-class-properties']
        }
      }
    }
  ]
}

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 set to true in options ({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 if you must continue using babel-loader directly, but still want to customize.

  • metadataSubscribers: Default []. Takes an array of context function names. E.g. if you passed ['myMetadataPlugin'], you'd assign a subscriber function to context.myMetadataPlugin within your webpack plugin's hooks & that function will be called with metadata.

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.

Some files in my node_modules are not transpiled for IE 11

Although we typically recommend not compiling node_modules, you may need to when using libraries that do not support IE 11 or any legacy targets.

For this, you can either use a combination of test and not, or pass a function to your exclude option. You can also use negative lookahead regex as suggested here.

{
    test: /\.(?:js|mjs|cjs)$/,
    exclude: {
      and: [/node_modules/], // Exclude libraries in node_modules ...
      not: [
        // Except for a few of them that needs to be transpiled because they use modern syntax
        /unfetch/,
        /d3-array|d3-scale/,
        /@hapi[\\/]joi-date/,
      ]
    },
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          ['@babel/preset-env', { targets: "ie 11" }]
        ]
      }
    }
  }

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: /\.(?:js|mjs|cjs)$/,
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          ['@babel/preset-env', { targets: "defaults" }]
        ],
        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: /\.(?:js|mjs|cjs)$/,
    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|mjs|cjs)$/,
    loader: 'babel-loader',
  }

Exclude libraries that should not be transpiled

core-js and webpack/buildin will cause errors if they are transpiled by Babel.

You will need to exclude them form babel-loader.

{
  "loader": "babel-loader",
  "options": {
    "exclude": [
      // \\ for Windows, / for macOS and Linux
      /node_modules[\\/]core-js/,
      /node_modules[\\/]webpack[\\/]buildin/,
    ],
    "presets": [
      "@babel/preset-env"
    ]
  }
}

Top level function (IIFE) is still arrow (on Webpack 5)

That function is injected by Webpack itself after running babel-loader. By default Webpack asumes that your target environment supports some ES2015 features, but you can overwrite this behavior using the output.environment Webpack option (documentation).

To avoid the top-level arrow function, you can use output.environment.arrowFunction:

// webpack.config.js
module.exports = {
  // ...
  output: {
    // ...
    environment: {
      // ...
      arrowFunction: false, // <-- this line does the trick
    },
  },
};

Customize config based on webpack target

Webpack supports bundling multiple targets. For cases where you may want different Babel configurations for each target (like web and node), this loader provides a target property via Babel's caller API.

For example, to change the environment targets passed to @babel/preset-env based on the webpack target:

// babel.config.js

module.exports = api => {
  return {
    plugins: [
      "@babel/plugin-proposal-nullish-coalescing-operator",
      "@babel/plugin-proposal-optional-chaining"
    ],
    presets: [
      [
        "@babel/preset-env",
        {
          useBuiltIns: "entry",
          // caller.target will be the same as the target option from webpack
          targets: api.caller(caller => caller && caller.target === "node")
            ? { node: "current" }
            : { chrome: "58", ie: "11" }
        }
      ]
    ]
  }
}

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 => {
  // Extract the custom options in the custom plugin
  function myPlugin(api, { opt1, opt2 }) {
    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, { 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 and passing it the customOptions object.
          [myPlugin, customOptions],
        ],
      };
    },

    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, options: { source, customOptions }): 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

More Repositories

1

babel

🐠 Babel is a compiler for writing next generation JavaScript.
TypeScript
42,835
star
2

minify

✂ī¸ An ES6+ aware minifier based on the Babel toolchain (beta)
JavaScript
4,375
star
3

babel-preset-env

PSA: this repo has been moved into babel/babel -->
JavaScript
3,502
star
4

babel-sublime

Syntax definitions for ES6 JavaScript with React JSX extensions.
JavaScript
3,260
star
5

babel-eslint

đŸ—ŧ A wrapper for Babel's parser used for ESLint (renamed to @babel/eslint-parser)
JavaScript
2,970
star
6

example-node-server

Example Node Server w/ Babel
JavaScript
2,842
star
7

babylon

PSA: moved into babel/babel as @babel/parser -->
JavaScript
1,714
star
8

babelify

Browserify transform for Babel
JavaScript
1,680
star
9

gulp-babel

Gulp plugin for Babel
JavaScript
1,322
star
10

babel-upgrade

âŦ†ī¸ A tool for upgrading Babel versions (to v7): `npx babel-upgrade`
JavaScript
1,308
star
11

awesome-babel

😎A list of awesome Babel plugins, presets, etc.
857
star
12

babel-standalone

🎮 Now located in the Babel repo! Standalone build of Babel for use in non-Node.js environments, including browsers.
JavaScript
821
star
13

preset-modules

A Babel preset that targets modern browsers by fixing engine bugs (will be merged into preset-env eventually)
JavaScript
740
star
14

website

🌐 The Babel documentation website
TypeScript
740
star
15

kneden

Transpile ES2017 async/await to vanilla ES6 Promise chains: a Babel plugin
JavaScript
514
star
16

grunt-babel

Grunt plugin for Babel
JavaScript
438
star
17

proposals

✍ī¸ Tracking the status of Babel's implementation of TC39 proposals (may be out of date)
433
star
18

eslint-plugin-babel

An ESlint rule plugin companion to babel-eslint
JavaScript
390
star
19

generator-babel-boilerplate

A Yeoman generator to author libraries in ES2015 (and beyond!) for Node and the browser.
JavaScript
381
star
20

babel-time-travel

Time travel through babel transformations one by one (implemented in the Babel REPL now)
JavaScript
345
star
21

babel-polyfills

A set of Babel plugins that enable injecting different polyfills with different strategies in your compiled code.
TypeScript
321
star
22

babel-sublime-snippets

Next generation JavaScript and React snippets for Sublime
264
star
23

karma-babel-preprocessor

Karma plugin for Babel
JavaScript
167
star
24

ruby-babel-transpiler

Ruby Babel is a bridge to the JS Babel transpiler.
Ruby
158
star
25

babel-jest

Jest plugin for Babel (moved) ->
139
star
26

notes

â™Ŧ Notes from the @Babel Team (discuss in PRs)
121
star
27

generator-babel-plugin

Babel Plugin generator for Yeoman
JavaScript
118
star
28

babel-bridge

A placeholder package that bridges babel-core to @babel/core.
JavaScript
94
star
29

babel-bot

🤖 A helpful bot to automate common tasks on Babel Issues/PRs
JavaScript
75
star
30

babel-brunch

Brunch plugin for Babel
JavaScript
69
star
31

broccoli-babel-transpiler

Broccoli plugin for Babel
JavaScript
58
star
32

jade-babel

Jade plugin for Babel
JavaScript
40
star
33

sandboxes

Babel repl-like codesandbox: check out link =>
JavaScript
39
star
34

jekyll-babel

A Babel converter for Jekyll.
Ruby
34
star
35

acorn-to-esprima

(unmaintained) Converts acorn tokens to esprima tokens
JavaScript
33
star
36

babel-connect

Connect plugin for Babel
JavaScript
27
star
37

podcast.babeljs.io

The Babel Podcast site!
JavaScript
25
star
38

phabricator-to-github

A tool to migrate phabricator issues to github
JavaScript
24
star
39

actions

Babel specific github actions 🤖
JavaScript
24
star
40

rfcs

RFCs for changes to Babel
21
star
41

metalsmith-babel

A Metalsmith plugin to compile JavaScript with Babel
JavaScript
20
star
42

babel-configuration-examples

WIP
JavaScript
18
star
43

duo-babel

Duo plugin for Babel
JavaScript
16
star
44

logo

Babel logo
15
star
45

parser_performance

JavaScript
13
star
46

babel-standalone-bower

Bower build of babel-standalone. See https://github.com/Daniel15/babel-standalone
JavaScript
10
star
47

gobble-babel

Gobble plugin for Babel
JavaScript
9
star
48

eslint-config-babel

ESLint config for all Babel repos
JavaScript
9
star
49

eslint-plugin-babel-plugin

A set of eslint rules to enforce best practices in the development of Babel plugins.
JavaScript
8
star
50

flavortown

what else?
7
star
51

.github

Community health files for the Babel organization
7
star
52

babel-archive

🗑 Packages that are deprecated or don't need to be updated
JavaScript
6
star
53

babel-test262-runner

Run test262 tests on Node 0.10 using Babel 7 and `core-js@3`.
JavaScript
6
star
54

babel-plugin-proposal-private-property-in-object

@babel/plugin-proposal-private-property-in-object, with an added warning for when depending on this package without explicitly listing it in dependencies or devDependencies
JavaScript
6
star
55

phabricator-redirects

↩ī¸ Redirects for old phabricator urls
HTML
5
star
56

babel-plugin-transform-async-functions

https://github.com/MatAtBread/fast-async/issues/46
4
star
57

slack-invite-link

Source of slack.babeljs.io
1
star