【问题标题】:Custom webpack substitutions like [name], [id], [hash], but I want to build my own substitution自定义 webpack 替换,例如 [name]、[id]、[hash],但我想构建自己的替换
【发布时间】:2018-05-11 04:58:14
【问题描述】:

具体来说,我想构建标签[camelCaseName],它将文件名(蛇大小写)转换为骆驼大小写。

但我似乎找不到任何关于如何构建自己的自定义替换的说明。我想知道是否有人对此有一些资源或示例。

谢谢。

【问题讨论】:

    标签: webpack webpack-2


    【解决方案1】:

    我想我已经通过查看处理 [name] (https://github.com/webpack/webpack/blob/master/lib/TemplatedPathPlugin.js) 的代码弄明白了。

    我们可以编写一个挂接到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);
            });
        }
    }
    

    以上代码支持替换[camelcasename]

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 2012-07-05
      • 2017-06-20
      • 2021-08-18
      • 1970-01-01
      相关资源
      最近更新 更多