Search code examples
webpackbabeljs

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


There is a cacheDirectory option in babel-loader. I can't figure out how to use it with the following webpack setup:

var compiler = webpack( {
    context: path.resolve( __dirname + "/../../" + rootModuleDir + "/" + modules[ module ] ),
    entry: "./index.jsx",
    resolve: {
        root: path.resolve( __dirname + "/../../assets/js/lib/react" ),
        extensions: [ "", ".js", ".jsx" ]
    },
    output: {
        path: targetDir,
        filename: modules[ module ] + ".js"
    },
    module: {
        loaders: [
            { test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader?optional=runtime" }
        ]
    },
    plugins: [
        //new webpack.optimize.UglifyJsPlugin(),
        new webpack.SourceMapDevToolPlugin( {
            filename: "[file].map"
        } )
    ]
} );

Where should it go?


Solution

  • 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