How to register a custom loader in webpack.config

Hi guys.
I have a problem with https://github.com/webpack/jade-loader. It always return a function, but i want this loader always return a string. So that I intend to write a custom loader that return a string from jade-loader template function. It is very simple, but how can i use it ?

module.exports = function(source) {
  console.log(source);
  return source();
};

I want to use like that “jade-loader -> template function -> jade-to-html -> return string -> ng-cache -> get this string for angular template-cache”.

var jadeToHtmlLoader = require('./jade-to-html-loader');
//How can i use like this. Thanks !
{test: /\.jade/, loader: "jade-loader!jade-to-html-loader!ng-cache?prefix=[dir]/[dir]"},

Author: Fantashit

7 thoughts on “How to register a custom loader in webpack.config

  1. @chenerlang666
    You can use the resolveLoader.alias config option which works the same way that resolve.alias works.

    For example:

      resolveLoader: {
        alias: {
          "jade-loader-custom": path.join(__dirname, "./jade-loader-custom")
        }
      },
      resolve: {
        modulesDirectories: ["src/scripts", "web_modules", "bower_components", "node_modules"],
        extensions: ["", ".js", ".coffee", ".json"],
        alias: require("./webpack-module-alias.js")
      },
  2. Since all the pieces to solve this puzzle are not here or on the linked pages:

    // my-project/build/webpack.config.js
    ...
      module: { 
        loaders: [
          { test: /\.foo$/, loader: 'bar?qux=qoo'}
        ]
      },
    ...
      resolveLoader: {
        fallback: [
          path.resolve(__dirname, 'loaders'),
          path.join(process.cwd(), 'node_modules')
        ]
      }
    ...
    foo: {
      bar: 'baz'
    }
    // my-project/build/loaders/foo-loader.js
    var utils = require('loader-utils'),
        debug = require('debug')('loader/foo');
    
    module.exports = function (source) {
      // do foo
     debug('start', source.length);
     var config = loaderUtils.getLoaderConfig(this, 'foo');
     debug('isBaz', config.bar === 'baz');
     debug('isQoo', config.qux === 'qoo');
     return source;
    }
  3. I paste my custom loader used in Webpack 2 for anyone interested in future:

    // Webpack config
    resolveLoader: {
        alias: {
          'readme-loader': path.join(__dirname, './scripts/readme-loader'),
        },
     }
    
    
    // In module.rules
    {
        test: /\.md$/,
        use: ['readme-loader'],
     }

    The readme-loader is very similar to raw-loader and exports an object with both parsed and raw markdown. The raw-loader is a very nice and easy to understand example of loader.

  4. This also works:

    // In module.rules
    {
        test: /\.js$/,
        loader: require.resolve('../loaders/your-loader'),
    }

Comments are closed.