templateParameters
- 类型: Record<string, unknown> | Function
- 默认值:
type DefaultParameters = {
  mountId: string; // 对应 html.mountId 配置
  entryName: string; // 入口名称
  assetPrefix: string; // 对应 output.assetPrefix 配置
  compilation: Compilation; // Rspack 的 compilation 对象
  // htmlWebpackPlugin 内置的参数
  // 详见 https://github.com/jantimon/html-webpack-plugin
  htmlWebpackPlugin: {
    tags: object;
    files: object;
    options: object;
  };
};
定义 HTML 模板中的参数,对应 html-webpack-plugin 的 templateParameters 配置项。
对象用法
如果 templateParameters 的值是一个对象,它会和默认参数通过 Object.assign 合并。
比如,如果你需要在 HTML 模板中使用 foo 参数,可以添加如下设置:
export default {
  html: {
    templateParameters: {
      foo: 'bar',
    },
  },
};
接下来,你可以在 HTML 模板中,通过 <%= foo %> 来读取参数:
<script>
  window.foo = '<%= foo %>';
</script>
编译后的 HTML 代码如下:
<script>
  window.foo = 'bar';
</script>
函数用法
type TemplateParametersFunction = (
  defaultValue: Record<string, unknown>,
  utils: { entryName: string },
) => Record<string, unknown> | void;
当 html.templateParameters 为 Function 类型时,函数接收两个参数:
- value:Rsbuild 的默认 templateParameters 配置。
- utils: 一个对象,其中包含了- entryName字段,对应当前入口的名称。
在 MPA(多页面应用)场景下,你可以基于入口名称设置不同的 templateParameters 参数:
export default {
  html: {
    templateParameters(defaultValue, { entryName }) {
      const params = {
        foo: {
          ...defaultValue,
          type: 'Foo',
        },
        bar: {
          ...defaultValue,
          type: 'Bar',
          hello: 'world',
        },
      };
      return params[entryName] || defaultValue;
    },
  },
};