8

我在学习 webpack 时遇到了loaders,它的定义loaders说它会转换你的代码,以便它可以包含在 javascriptbundle中。

但是,html-loader 是如何工作的?

定义说它将 html 导出为字符串(这html-loader是什么意思)。

它还说每个可加载的属性(例如<img src="image.png"导入为require('./image.png'),并且您可能需要在配置(file-loaderurl-loader)中为图像指定加载器,这是什么意思。

我想知道,html-loader 到底做了什么。它是转换html为 String 还是只是将img标签转换为require. 这一切如何协同工作。

谁能详细解释一下。

4

2 回答 2

0

由于 webpack 在 5.0 中彻底改变了它的工作方式。“将 HTML 导出为字符串”不再是对用例的最佳描述。过去,人们会将 html-loader 与 extract-loader 和 file-loader 链接起来以发出 html。现在,无论出于何种原因,我都会使用它来解析 html。 https://v4.webpack.js.org/loaders/extract-loader/

于 2021-07-03T04:16:28.870 回答
-1

正如您可以从https://webpack.js.org/loaders/html-loader/

这不仅仅是转换成字符串。

您可以预处理 html,例如向变量添加值,您可以应用过滤器,......仅举几例

module.exports = {
  module: {
    rules: [
      {
        test: /\.html$/i,
        loader: 'html-loader',
        options: {
          attributes: {
            list: [
              {
                // Tag name
                tag: 'img',
                // Attribute name
                attribute: 'src',
                // Type of processing, can be `src` or `scrset`
                type: 'src',
              },
              {
                // Tag name
                tag: 'img',
                // Attribute name
                attribute: 'srcset',
                // Type of processing, can be `src` or `scrset`
                type: 'srcset',
              },
              {
                tag: 'img',
                attribute: 'data-src',
                type: 'src',
              },
              {
                tag: 'img',
                attribute: 'data-srcset',
                type: 'srcset',
              },
              {
                // Tag name
                tag: 'link',
                // Attribute name
                attribute: 'href',
                // Type of processing, can be `src` or `scrset`
                type: 'src',
                // Allow to filter some attributes
                filter: (tag, attribute, attributes, resourcePath) => {
                  // The `tag` argument contains a name of the HTML tag.
                  // The `attribute` argument contains a name of the HTML attribute.
                  // The `attributes` argument contains all attributes of the tag.
                  // The `resourcePath` argument contains a path to the loaded HTML file.

                  if (/my-html\.html$/.test(resourcePath)) {
                    return false;
                  }

                  if (!/stylesheet/i.test(attributes.rel)) {
                    return false;
                  }

                  if (
                    attributes.type &&
                    attributes.type.trim().toLowerCase() !== 'text/css'
                  ) {
                    return false;
                  }

                  return true;
                },
              },
            ],
          },
        },
      },
    ],
  },
};

上面的代码取自链接,这是一个过滤的例子。

或者,您也可以使用此插件html-webpack-plugin

于 2020-06-08T05:52:16.553 回答