问题描述
我有一个带有 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',}),
<!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
不存在。
解决方法
实际上,我可以做得更容易。事实证明,我可以将 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 %>