使用HTML Webpack插件需要变量

4
基于这个示例(https://github.com/ampedandwired/html-webpack-plugin/tree/master/examples/custom-template),我创建了一个类似的设置,它通过环境变量需要子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' ) %>

没有上下文就无法工作。 尝试 <% require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) %> - jantimon
感谢您的回复。 - Hanterdro
现在错误已经消失了,但是模板没有被包含进来。我个人认为,在执行 require 时,webpack html 插件的环境可能还不可用。也许这是插件的问题? - Hanterdro
2个回答

2
${ require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) }

无论使用${}还是<% %>,在此插件中它们都是等效的。

必须像以下这样设置加载器路径:html../。其中../不能从外部传递进来。

也可以使用<%=require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) %> 这种方式。

但是使用 ${ require('html!' + htmlWebpackPlugin.options.environment.templateUrl + '.html' ) } 的方式(路径中包含./)不够高效。


0

好的,我找到了解决方案。除了添加上下文之外,还需要将<%更改为${。我不明白或不知道为什么,但它有效。

${ require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) }

你有任何想法为什么这样可以工作吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接