我有充满任意 css/html/js/图像文件的模板文件夹。我希望能够通过要求访问它们:
var someHtml = require('./templateFolder/foo.html');
这里,foo.html
包含对 foo.png
、foo.css
和 foo.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 文件的外观,我不一定有很多控制权。
最佳答案
看起来您可以为您的用例使用 webpack 的 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");
有关更多信息,请查看上面的链接!
编辑:
例如,要自动内联图像,您可以使用 attrs
参数:
By default every local is required (require('./image.png')). You may need to specify loaders for images in your configuration (recommended file-loader or url-loader).
You can specify which tag-attribute combination should be processed by this loader via the query parameter attrs. Pass an array or a space-separated list of : combinations. (Default: attrs=img:src)
编辑: 要对样式表链接和 js 执行相同操作,您可以使用 https://www.npmjs.com/package/html-inline-source-webpack-plugin
关于javascript - 我如何使用 webpack 来要求包含内联 CSS、JS 和 PNG 的 HTML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46668797/