【问题标题】:What exactly am I supposed to do with "module.exports = 'html_template_content'" on webpack我到底应该用 webpack 上的“module.exports = 'html_template_content'”做什么
【发布时间】:2016-12-06 04:14:22
【问题描述】:

所以我想用 webpack 做一个非常简单的任务。

我有一些静态 HTML 模板,例如

test.html

<div><span>template content</span></div>

我想要做的就是返回模板内的字符串 例如

require("raw!./test.html")

with 应该返回一个类似的字符串:

"<div><span>template content</span></div>"

但相反,它返回以下字符串

"modules.exports = <div><span>template content</span></div>"

我尝试了几个模块,例如 raw-loader 和 html-loader。 并且它们的行为方式相同。所以我查看了源代码,只是为了发现它的 SUPPOSED 行为方式。

如果我只想要原始的 HTML?只是删除前置是一种不好的做法 “module.exports =”字符串?从捆绑 编辑:删除 'modules.export =' 部分会导致捆绑包不返回任何内容:/

我的配置

module.exports =
{
    module:
    {
        loaders:
            [
                { test: /\.html$/, loader: "raw-loader" }
            ]
    }
};

【问题讨论】:

  • 你能展示你的 webpack 配置吗?返回 module.exports 大概是内部 webpack 的事情 - 你应该得到一个原始字符串
  • 我在上面发布了配置

标签: node.js npm webpack webpack-html-loader raw-loader


【解决方案1】:

当您编写require('./test.html') 时,这意味着您只需运行加载程序链返回的代码。结果在此代码中导出为module.exports。要使用此结果,您需要将 require 语句分配给变量:

var htmlString = require('raw!./test.html');
//htmlString === "<div><span>template content</span></div>"

请记住,Webpack 中的任何加载器都返回 JS 代码——不是 HTML,不是 CSS。您可以使用此代码来获取 HTML、CSS 等。

【讨论】:

  • 哎呀,这是 OP 中的错字,我已经在使用 require('raw!./test.html'),它返回相同的字符串
【解决方案2】:

解决方案是在不指定任何其他加载程序的情况下要求您的文件,因为这已在 webpack 配置中指定

const test = require('./test.html')

说明:使用您当前的代码,您将两次应用raw 加载程序到您的文件。当您在配置中指定加载器链时:

loaders:
    [
        { test: /\.html$/, loader: "raw-loader" }
    ]

...你已经在告诉 webpack 每次需要一个匹配 test 条件的文件(这里是每个 html 文件)时都将这个加载器添加到加载器链中

因此,当你写这个

const test = require('raw!./test.html')

...其实就相当于这个

const test = require('raw!raw!./test.html')

【讨论】:

    【解决方案3】:

    我终于想通了。需要使用require.resolve(./test.html)https://nodejs.org/dist/latest-v7.x/docs/api/globals.html#globals_require解析路径名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多