【问题标题】:Require variable with HTML Webpack Plugin需要带有 HTML Webpack 插件的变量
【发布时间】:2016-04-03 15:46:16
【问题描述】:

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

【问题讨论】:

  • 没有上下文是行不通的。试试&lt;% require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) %&gt;
  • 感谢您的回复。
  • 现在错误消失了,但是没有包含模板。我个人认为,在执行 require 的那一刻,来自 webpack html 插件的环境是不可用的。也许是插件的问题?

标签: webpack


【解决方案1】:
${ require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) }

我发现任何使用 ${ 或 html../ 这样设置 loader 路径,../ 不能传出去。

&lt;%=require('html!./' +htmlWebpackPlugin.options.environment.templateUrl + '.html' ) %&gt;也可以。

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

【讨论】:

    【解决方案2】:

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

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

    知道为什么会这样吗?

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 2017-12-22
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 2014-06-15
      • 2021-07-16
      相关资源
      最近更新 更多