基于此示例(https://github.com/ampedandwired/html-webpack-plugin/tree/master/examples/custom-template)我创建了一个类似的设置,它需要通过环境var的子html文件。
function generate_page(config) {
var tempateUrl = config.templateUrl ? config.templateUrl : 'src/template.html';
return new HtmlWebpackPlugin({
filename: config.filename,
template: tempateUrl,
xhtml: true,
environment: {templateUrl: config. subTemplateUrl}
});
}
我的src / template.html需要此子模板:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<% require('html!'+ htmlWebpackPlugin.options.environment.templateUrl ) %>
</body>
</html>
但是当我运行webpack --progress --colors --watch -d
时,我发现了这个错误:
ERROR in Template execution failed: Error: Cannot find module "."
ERROR in Error: Cannot find module "."
- template.html:57 webpackMissingModule
/Users/xxx/PycharmProjects/webpack-test/src/template.html:57:47
- template.html:57
/Users/xxx/PycharmProjects/webpack-test/src/template.html:57:125
- template.html:62 module.exports
/Users/xxx/PycharmProjects/webpack-test/src/template.html:62:4
- index.js:228
[webpack-test]/[html-webpack-plugin]/index.js:228:16
- util.js:16 tryCatcher
[webpack-test]/[bluebird]/js/release/util.js:16:23
- promise.js:503 Promise._settlePromiseFromHandler
[webpack-test]/[bluebird]/js/release/promise.js:503:31
- promise.js:560 Promise._settlePromise
[webpack-test]/[bluebird]/js/release/promise.js:560:18
- promise.js:597 Promise._settlePromiseCtx
[webpack-test]/[bluebird]/js/release/promise.js:597:10
- async.js:131 Async._drainQueue
[webpack-test]/[bluebird]/js/release/async.js:131:12
- async.js:136 Async._drainQueues
[webpack-test]/[bluebird]/js/release/async.js:136:10
如果我在template.html文件中编写相同的subTemplateUrl而不是变量,那么一切正常:
<% require('html!./test.html' ) %>
答案 0 :(得分:2)
${ require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) }
我发现任何使用$ {或&lt;%即可。它在这个插件中都是相同的。
require必须设置像html../
这样的加载器路径,../
无法从中传出。
<%=require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) %>
也没关系。
但使用${ require('html!' + htmlWebpackPlugin.options.environment.templateUrl + '.html' ) }
(路径./
包含在templateUrl变量中)的方式效率不高。
答案 1 :(得分:0)
好的,我找到了解决方案。除了添加上下文之外,还需要将<%
更改为${
。我不明白或不知道为什么,但它确实有效。
${ require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) }
知道为什么会这样吗?