将JS / CSS / HTML合并为单个HTML

时间:2017-06-20 07:25:38

标签: javascript html css

我有一个包含2个HTML文件,6个CSS文件和11个JS文件的小型本地Web应用程序。

  1. 如果所有这些文件都是,那么网络应用程序是否仍然有效 (正确地)复制粘贴在单个HTML文件中,例如将JS放入 标头中有<script>个标签,并将CSS放入<style>标签?

  2. 有没有人知道可以使用的工具 自动安全地合并JS,CSS和HTML的集合 将文件转换为单个HTML?

  3. 在线搜索,我找到的工具一次只能合并或缩小一种类型的文件,但不能创建合并的HTML文件(例如AIOM+HTMLcompressor。 我确实找到了这个名为Inliner的应用程序,但似乎它运行在Node.js上,我不熟悉并且目前不使用它。

    简而言之,我正在寻找一种可以读取HTML中所有链接文件的简单独立工具,并通过附加这些文件的内容来重写HTML。如果这要求太多,那么只需确认手动执行该工作就会产生一个工作文件,或者在执行此操作时需要考虑的任何提示。谢谢!

2 个答案:

答案 0 :(得分:3)

我为此编写了一个简单的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中用linkscript标签指定的文件中的所有js和css。
您可以在任何地方使用此文件。

注意:

  1. HTML文件的根文件夹中必须为“ index.html”。
  2. 它仅适用于单个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))

答案 1 :(得分:0)

您可以考虑使用webpack。一开始并不容易理解,但开始时这是一个很好的tutorial

相关问题