Which is Better TypeScript Loaders for Webpack?
babel-loader vs ts-loader vs awesome-typescript-loader
1 Year
babel-loaderts-loaderawesome-typescript-loader
What's TypeScript Loaders for Webpack?

TypeScript loaders are essential tools in the Webpack ecosystem that facilitate the integration of TypeScript into JavaScript applications. They enable developers to compile TypeScript code into JavaScript, allowing for type safety and modern JavaScript features while maintaining compatibility with existing JavaScript codebases. Each loader has its unique features and optimizations, catering to different project requirements and developer preferences. Understanding the differences among these loaders is crucial for selecting the right one for your project, ensuring efficient build processes and optimal performance.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
babel-loader16,965,9904,82138.8 kB6220 days agoMIT
ts-loader6,742,1493,450258 kB80a year agoMIT
awesome-typescript-loader87,9922,351-2336 years agoMIT
Feature Comparison: babel-loader vs ts-loader vs awesome-typescript-loader

Performance

  • babel-loader: babel-loader is generally slower for TypeScript files compared to dedicated TypeScript loaders, as it relies on Babel's transformation process. However, it can be optimized with caching and parallel processing for better performance in mixed codebases.
  • ts-loader: ts-loader offers decent performance but may not be as fast as awesome-typescript-loader in large projects. It compiles TypeScript files directly using the TypeScript compiler, which can be slower for larger codebases but provides accurate type checking.
  • awesome-typescript-loader: awesome-typescript-loader is optimized for performance, featuring a caching mechanism that speeds up incremental builds. It compiles TypeScript files only when necessary, reducing build times significantly in large projects.

Type Checking

  • babel-loader: babel-loader does not perform type checking by default, as it focuses on transpilation. Developers need to run a separate TypeScript compiler process to catch type errors, which may lead to missed issues during development.
  • ts-loader: ts-loader provides built-in type checking, allowing developers to catch type errors during the build process. It can be configured to run type checking in parallel or as a separate step to improve build performance.
  • awesome-typescript-loader: awesome-typescript-loader performs type checking during the build process, ensuring that type errors are caught early. It leverages TypeScript's compiler API for accurate diagnostics, making it suitable for large applications.

Configuration Complexity

  • babel-loader: babel-loader has a straightforward configuration process, especially for projects already using Babel. It allows for easy integration of TypeScript alongside other JavaScript features, making it user-friendly for mixed environments.
  • ts-loader: ts-loader is relatively easy to configure, especially for TypeScript-centric projects. It requires minimal setup to get started, making it a good choice for developers who want a simple integration with TypeScript.
  • awesome-typescript-loader: awesome-typescript-loader requires additional configuration for optimal performance and caching. While it offers advanced features, the setup can be more complex compared to simpler loaders.

Ecosystem Compatibility

  • babel-loader: babel-loader is highly compatible with the Babel ecosystem, allowing for the use of various Babel plugins and presets. This makes it a versatile choice for projects that require extensive JavaScript transformations alongside TypeScript.
  • ts-loader: ts-loader is the most commonly used TypeScript loader in the Webpack ecosystem, ensuring broad compatibility with TypeScript features and community support. It is often recommended for TypeScript-only projects.
  • awesome-typescript-loader: awesome-typescript-loader is designed specifically for Webpack and works well with its ecosystem. However, it may not be as widely adopted as ts-loader, leading to fewer community resources and examples.

Community Support

  • babel-loader: babel-loader has a large community and extensive documentation, making it easy to find support and resources. It is widely used in the JavaScript ecosystem, which enhances its reliability and support.
  • ts-loader: ts-loader has strong community support and is the recommended loader for TypeScript in Webpack. It has comprehensive documentation and a wealth of community resources, making it a safe choice for TypeScript projects.
  • awesome-typescript-loader: awesome-typescript-loader has a smaller community compared to ts-loader, which may result in fewer resources and documentation. However, it is still actively maintained and used in various projects.
How to Choose: babel-loader vs ts-loader vs awesome-typescript-loader
  • babel-loader: Choose babel-loader if you need to transpile both TypeScript and modern JavaScript (ES6+) code, especially when working with a mixed codebase. It is ideal for projects that require extensive use of Babel plugins and presets for additional transformations and optimizations.
  • ts-loader: Choose ts-loader if you prefer a straightforward integration with TypeScript's compiler (tsc) and need full support for TypeScript features such as type checking and source maps. It is particularly useful for projects that are heavily TypeScript-focused and require accurate type checking during the build process.
  • awesome-typescript-loader: Choose awesome-typescript-loader if you prioritize performance and want to take advantage of its caching mechanism, which can significantly speed up builds in large projects. It is particularly beneficial if you are using Webpack 3 or earlier versions.
README for babel-loader

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

The options passed here will be merged with Babel config files, e.g. babel.config.js or .babelrc.

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 and the babel-loader's version
    • the merged Babel config, including options passed to babel-loader and the contents of babel.config.js or .babelrc file if they exist
    • 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