使用动态路径加载自定义模板

时间:2021-05-05 15:20:12

标签: webpack html-webpack-plugin

我有一个带有 webpack 1.14.0 的过时 web 项目。在项目中,html-webpack-plugin 用于生成 HTML 文件。这是 webpack 配置:

new HtmlWebpackPlugin({
      title: 'title',
      banner: banner,
      publicPath: (debug ? `http://${ipToUse}:8080/` : fullDeployPath),
      chunks: ['home'],
      is_debug: debug,
      template: path.join(__dirname, 'lib', 'template.ejs'),
      inject: 'body',
      filename: 'index.html',
    }),

这是一个 template.ejs 文件:

<!DOCTYPE html>
<html>
  <head>
    <title><%= htmlWebpackPlugin.options.title %></title>
    <meta charset="utf-8">
    <%= require('html!./cmp.html') %>
    <link rel="apple-touch-icon" href="<%= htmlWebpackPlugin.options.publicPath %>assets/touch-icon.png" />
    <link rel="icon" sizes="192x192" href="<%= htmlWebpackPlugin.options.publicPath %>assets/touch-icon.png" />
    <link rel="icon" type="image/x-icon" href="<%= htmlWebpackPlugin.options.publicPath %>assets/logo.ico" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
  </head>
  <body>
    <div id="main-app"></div>
  </body>
</html>

如您所见,我在那里加载了一个自定义模板 (require('html!./cmp.html'))。我用那个html-loader

问题是:需要路径 html!./cmp.html 是否可能依赖于 HtmlWebpackPlugin 配置。换句话说,我想要这样的东西:

new HtmlWebpackPlugin(
   pathToTemplate: './some/path/head_template.html'
   // other options
)

然后在模板中(或类似的东西):

<%= require('html!' + htmlWebpackPlugin.options.pathToTemplate) %>

这对我不起作用。我猜加载器和插件不是同时运行的。当 require 尝试加载模板时 htmlWebpackPlugin.options.pathToTemplate 不存在。

1 个答案:

答案 0 :(得分:0)

实际上,我可以做得更容易。事实证明,我可以将 HTML 字符串作为 HtmlWebpackPlugin 配置传递,例如。

new HtmlWebpackPlugin(
   snippet: '<h1>Some title</h1>'
   // other options
)

所以我可以在我的 webpack 配置文件中读取文件,例如。

const snippet = (() => {
  try {
    const snippet = fs.readFileSync(`./clients/${argv.client}/templates/snippet.html`);
    return snippet;
  } catch(err) {
    return '';
  }
})();


// later when I configure HtmlWebpackPlugin
new HtmlWebpackPlugin(
   snippet,
// other options
)

在模板中,我将其用作任何其他选项:

<%= htmlWebpackPlugin.options.snippet %>