【问题标题】:How do I use webpack to be able to require an HTML document with inlined CSS, JS and PNG如何使用 webpack 来要求具有内联 CSS、JS 和 PNG 的 HTML 文档
【发布时间】:2017-10-10 14:03:45
【问题描述】:

我有充满任意 css/html/js/image 文件的模板文件夹。我希望能够通过 require 访问它们:

var someHtml = require('./templateFolder/foo.html');

这里,foo.html 包含对 foo.pngfoo.cssfoo.js 的引用,我希望它们都内联在 html 文档本身中,分别以 base64 编码、样式标记和脚本标记。这可能吗?如果是这样,webpack 配置会是什么样子?

编辑:进一步的上下文

我想要这个

<html>
  <head>
      <link rel="stylesheet" type="text/css" href="foo.css">
      <script type="text/javascript" src="bar.js"></script>
  </head>
  <body>
  </body
</html>

变成这样:

<html>
  <head>
      <style> Contents of foo.css </style>
      <script> Contents of bar.js</script>
  </head>
  <body>
  </body
</html>

换句话说,我希望将每个 html 文件及其所有资源转换为单个 html 文件。对于 html 文件的外观,我不一定有很多控制权。

【问题讨论】:

    标签: javascript html css webpack


    【解决方案1】:

    看起来您可以将html-loader 用于您的用例: https://github.com/webpack-contrib/html-loader

    一个示例 webpack.config 文件将包括:

    module: {
      rules: [{
        test: /\.html$/,
        use: [ {
          loader: 'html-loader',
          options: {
            minimize: true
          }
        }],
      }]
    }
    

    然后您应该能够使用 require("html-loader!./file.html"); 获取所需的 html 文件

    欲了解更多信息,请查看上面的链接!


    编辑: 例如,要自动内联图像,您可以使用attrs 参数:

    默认情况下,每个本地都是必需的 (require('./image.png'))。您可能需要在配置中为图像指定加载器(推荐使用文件加载器或 url-loader)。

    您可以通过查询参数 attrs 指定此加载器应处理的标记属性组合。传递数组或空格分隔的 : 组合列表。 (默认:attrs=img:src)


    编辑: 要对样式表链接和 js 执行相同操作,您可以使用 https://www.npmjs.com/package/html-inline-source-webpack-plugin

    【讨论】:

    • 嗯,这会内联css、js和png吗?
    • 我想我一定是问错了问题。我想从 html 中得到这样的东西:&lt;script src="foo.js"&gt; 看起来像这样 &lt;script&gt; /*contents of foo.js */ &lt;/script&gt; 和链接:href 做类似的事情。有什么想法吗?
    猜你喜欢
    • 2019-05-13
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多