需要使用HTML Webpack插件的变量

基于此示例(
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' ) %>

最佳答案

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

我发现任何使用${或<%即可.它在这个插件中都是相同的.
require必须设置像这个html ../的加载器路径,.. /不能从中传出.

<%= require(‘html!./’htmlWebpackPlugin.options.environment.templateUrl’.html’)%>它也没关系.

但是使用${require(‘html!’htmlWebpackPlugin.options.environment.templateUrl’.html’)}(在templateUrl变量中包含./include)的方式效率不高.

点赞