How to specify cacheDirectory option when using babel-loader with webpack?

You can add it to the babel-loader configuration like this:

loaders: [
    {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: "babel-loader?optional=runtime&cacheDirectory"
    }
]

Note, you should not add =true, that's unnecessary and will set the cacheDirectory to be use a directory named true. Reference: using cacheDirectory fails with Error

You can also use the query property:

rules: [
    {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        query: {
            optional: "runtime",
            cacheDirectory: true
        }
    }
]

When using the query property, specifying true will enable the option, and specifying a string value will enable the option and configure it to use that directory name. Reference: query parameters


Add it to the loader string like so:

module: {
    loaders: [
        { test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader?optional=runtime&cacheDirectory=true" }
    ]
},

You can do it like this -

module.exports = {
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader?+cacheDirectory'
      }
    ]
  } 
};


It will cache in node_modules/.cache/babel-loader folder.

Files would be stored something like this -

0065e42bfc1ab4c292dfa71c6a0e924b59ed6a37.json.gz 538205e2b3bffa535d934c3d8f2feee4566bfc00.json.gz b17d9d4b73726f4ba7c5797a9959546fb3d72d69.json.gz

Different cache file for each JS file.

Refer documentation here - https://webpack.js.org/loaders/babel-loader/#options