Search code examples
webpackwebpack-2

Custom webpack substitutions like [name], [id], [hash], but I want to build my own substitution


Specifically, I want to build the tag [camelCaseName] that will convert file name (which is in snake case) to the camel case.

But I can't seem to find any instruction on how to build my own custom substitution. I wonder if anyone has some resources or examples around this.

Thank you.


Solution

  • I think I've figured it out from looking at the code that handles [name] (https://github.com/webpack/webpack/blob/master/lib/TemplatedPathPlugin.js).

    We can write a plugin that hooks in to asset-path.

    const replacePathVariables = (path, data) => {
      const REGEXP_CAMEL_CASE_NAME = /\[camelcasename\]/gi;
        if (typeof path === "function") {
            path = path(data);
        }
    
      if (data && data.chunk && data.chunk.name) {
        return path.replace(
          REGEXP_CAMEL_CASE_NAME,
          data.chunk.name
            .replace(/(\-\w)/g, (matches) => { return matches[1].toUpperCase(); })
            .replace(/(^\w)/, (matches) => { return matches[0].toUpperCase(); })
        );
      } else {
        return path;
      }
    
    };
    
    class ExtraTemplatedPathPlugin {
        apply(compiler) {
        compiler.plugin("compilation", function(compilation) {
                const mainTemplate = compilation.mainTemplate;
                mainTemplate.plugin('asset-path', replacePathVariables);
            });
        }
    }
    

    The code above supports replacing [camelcasename].