我有一个小型本地 Web 应用程序,包含 2 个 HTML 文件、6 个 CSS 文件和 11 个 JS 文件。
如果所有这些文件都被删除,网络应用程序是否仍然可以工作 (正确地)复制粘贴到单个 HTML 文件中,例如把JS放进去
<script>
header 中的标签,并将 CSS 放入<style>
标签?有谁知道有一个工具可以 自动、安全地合并 JS、CSS 和 HTML 的集合 文件转换为单个 HTML?
在网上搜索,我只找到可以一次合并或缩小一种类型的文件的工具,但不能创建合并的 HTML 文件(例如 AIOM+ 、 HTMLcompressor . 我确实找到了这个名为 Inliner 的应用程序,但它似乎在 Node.js 上运行,我对此并不熟悉,目前也没有使用。
简而言之,我正在寻找一个简单的独立工具,可以读取 HTML 中的所有链接文件,并通过附加这些文件的内容来重写 HTML。如果要求太多,那么只需确认手动完成该工作将产生一个工作文件,或者在执行此操作时需要考虑的任何提示。谢谢!
最佳答案
我为它编写了一个简单的Python脚本。
这是我的树:
root-folder
├── index.html
├── build_dist.py
├── js
│ └── somescript.js
├── css
│ ├── styles1.css
│ └── styles2.css
└── dist
我运行脚本:
cd root-folder
python build_dist.py
并且在dist文件夹中创建了一个oneindex.html文件。
该文件包含index.html中使用link
和script
标记指定的文件中的所有js和css。
您可以在任何地方使用此文件。
注意:
- HTML 文件必须是根文件夹中的“index.html”。
- 它仅适用于单个 HTML 文件。我不知道您想对多个 HTML 文件做什么。
build_dist.py代码:
# build_dist.py
from bs4 import BeautifulSoup
from pathlib import Path
import base64
original_html_text = Path('index.html').read_text(encoding="utf-8")
soup = BeautifulSoup(original_html_text)
# Find link tags. example: <link rel="stylesheet" href="css/somestyle.css">
for tag in soup.find_all('link', href=True):
if tag.has_attr('href'):
file_text = Path(tag['href']).read_text(encoding="utf-8")
# remove the tag from soup
tag.extract()
# insert style element
new_style = soup.new_tag('style')
new_style.string = file_text
soup.html.head.append(new_style)
# Find script tags. example: <script src="js/somescript.js"></script>
for tag in soup.find_all('script', src=True):
if tag.has_attr('src'):
file_text = Path(tag['src']).read_text()
# remove the tag from soup
tag.extract()
# insert script element
new_script = soup.new_tag('script')
new_script.string = file_text
soup.html.body.append(new_script)
# Find image tags.
for tag in soup.find_all('img', src=True):
if tag.has_attr('src'):
file_content = Path(tag['src']).read_bytes()
# replace filename with base64 of the content of the file
base64_file_content = base64.b64encode(file_content)
tag['src'] = "data:image/png;base64, {}".format(base64_file_content.decode('ascii'))
# Save onefile
with open("dist/oneindex.html", "w", encoding="utf-8") as outfile:
outfile.write(str(soup))
关于javascript - 将 JS/CSS/HTML 合并为单个 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44646481/