Search code examples
webpackwebpack-4webpack-loader

Webpack 4: Creating loaders as functions (with the ability to send options)


I may be missing something obvious, but I can't seem to be able to create a Webpack 4 loader as a simple function that can take options:

rules: [{
  test: /\.csv$/,
  loader: function() {
    // ...
  },
  options: {
    // ...
  }
}]

I dare not assume Webpack is so obstinate about loaders having to be npm packages, but I'm struggling to find an example where using a simple function as a loader works as intended.

Can someone help we with the most basic example of how to get something like this to work?

P.S. in the example config above, the function is imported from another file, just added it inline for clarity.


Solution

  • A Webpack loader should simply export a function that returns a string of code and an optional source map.

    var loaderUtils = require('loader-utils');
    
    export default function(source) {
        const options = loaderUtils.getOptions(this) || {};
        // Get the value of options.testOption from Webpack config
        var testOption = options.testOption;
    
        // ...
    
        return `export default ${JSON.stringify(source)}`;
    }
    

    This is a barebones example. loader-utils is used in most loaders to easily get the options passed to it from the Webpack configuration file. schema-utils can also be incorporated to validate the options.

    As for where to put this code, write it in a file named loader.js in whatever directory you want. Use it in your Webpack configuration with something like this:

    rules: [{
        test: /\.csv$/,
        use: {
            loader: path.resolve(__dirname, 'src/loader.js'),
            options: {
                testOption: 'test string'
            }
        }
    }]
    

    See Webpack's guide to writing a loader for more information.