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

10

我有一个由2个HTML文件、6个CSS文件和11个JS文件组成的小型本地Web应用程序。

  1. 如果这些文件都复制粘贴到单个HTML文件中(适当地),例如将JS放在头部的<script>标签中,将CSS放在<style>标签中,那么Web应用程序还能正常工作吗?

  2. 是否有工具可以自动且安全地将JS、CSS和HTML文件集合合并为单个HTML文件?

在网上搜索时,我只发现可以合并或压缩一种类型文件的工具,但没有创建合并HTML文件的工具(例如AIOM+HTMLcompressor)。我找到了这个名为Inliner的应用程序,但似乎是在我不熟悉并且当前不使用的Node.js上运行的。

简而言之,我要么寻找一个简单的独立工具,可以读取HTML中所有链接的文件,并通过附加这些文件的内容来重写HTML。如果这太困难了,那么只需确认手动完成工作将产生一个可用的文件,或者在这样做时需要注意的任何提示。谢谢!


1
可以将<style>放在<head>中,而将<script>放在结尾位置(但仍在<body>内部)。 - marcellothearcane
1
可能感兴趣的链接:https://dev59.com/FHA75IYBdhLWcg3wubun,https://dev59.com/3Yfca4cB1Zd3GeqPhVNg,https://dev59.com/WGs05IYBdhLWcg3wFOG8 - marcellothearcane
1
你第一个问题的答案是肯定的。至于你的第二个问题,寻求工具是违反 SO 政策的。 - Racil Hilan
谢谢您的评论,链接的问题中有一些有趣的东西,但也不完全是我需要的。我将尝试手动复制粘贴并遵循这些建议,看看是否可行。 - sc28
@sc28,你找到解决方案了吗? - mzuba
3个回答

6

我为此编写了一份简单的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中使用和

2
你可以考虑使用webpack。一开始可能不容易理解,但这是一个很好的tutorial入门教程。

1

1.

一般来说,是的。

2.

我不知道如何合并多个HTML文件,但是这里有一个Python脚本(Github),可以将CSS / JS /图像合并到一个单独的HTML文件中。与Noam Nol的回答相比...

  • ... 它没有外部依赖
  • ... 它还会正确处理非PNG图像。

用法: python3 htmlmerger yourfile.html

Github上的代码:htmlmerger.py

以下是Github文件的内容。

from html.parser import HTMLParser
import os
import sys
import base64


gHelp = """
Merge JS/CSS/images/HTML into one single file
Version: 1.0

Usage:
  htmlmerger inputfile [optional: outputfile]

"""


def getFileContent (strFilepath):
  content = ""
  with open (strFilepath, "r") as file:
    content = file.read ()
  return content



def getFileContentBytes (strFilepath):
  content = b""
  with open (strFilepath, "rb") as file:
    content = file.read ()
  return content


class HtmlMerger(HTMLParser):
  """
    Call "run(htmlContent, basedir)"  to merge
    script/css/images referenced withing htmlContent
    into one single html file.
  """
  def __init__(self):
    super().__init__()
    self._result = ""
    self._additionalData = ""
    self._baseDir = ""
    self.messages = []



  def _addMessage_fileNotFound(self, file_asInHtmlFile, file_searchpath):
    self.messages.append ("Error: Line " + str (self.getpos ()[0]) +
                        ": Could not find file `" + str (file_asInHtmlFile) +
                        "`; searched in `" + str (file_searchpath) + "`." )



  def _getAttribute (self, attributes, attributeName):
    """Return attribute value or `None`, if not existend"""
    for attr in attributes:
      key = attr[0]
      if (key == attributeName):
        return attr[1]
    return None


  def _getFullFilepath (self, relPath):
    return os.path.join (self._baseDir, relPath)


  def handle_starttag(self, tag, attrs):

    # Style references are within `link` tags. So we have to
    #  convert the whole tag
    if (tag == "link"):
      href = self._getAttribute (attrs, "href")
      if (href):
        hrefFullPath = self._getFullFilepath (href)
        if (not os.path.isfile (hrefFullPath)):
          self._addMessage_fileNotFound (href, hrefFullPath)
          return
        styleContent = getFileContent (hrefFullPath)
        self._result += "<style>" + styleContent + "</style>"
        return

    self._result += "<" + tag + " "

    for attr in attrs:
      key = attr[0]
      value = attr[1]

      # main work: read source content and add it to the file
      if (tag == "script" and key == "src"):
        #self._result += "type='text/javascript'"
        strReferencedFile = self._getFullFilepath (value)
        if (not os.path.isfile (strReferencedFile)):
          self._addMessage_fileNotFound (value, strReferencedFile)
          continue
        referencedContent = getFileContent (strReferencedFile)
        self._additionalData += referencedContent

        # do not process this key
        continue

      if (tag == "img" and key == "src"):
        imgPathRel = value
        imgPathFull = self._getFullFilepath (imgPathRel)
        if (not os.path.isfile (imgPathFull)):
          self._addMessage_fileNotFound (imgPathRel, imgPathFull)
          continue

        imageExtension = os.path.splitext (imgPathRel)[1][1:]
        imageFormat = imageExtension

        # convert image data into browser-undertandable src value
        image_bytes = getFileContentBytes (imgPathFull)
        image_base64 = base64.b64encode (image_bytes)
        src_content = "data:image/{};base64, {}".format(imageFormat,image_base64.decode('ascii'))
        self._result += "src='" + src_content + "'"

        continue



      # choose the right quotes
      if ('"' in value):
        self._result += key + "='" + value + "' "
      else:
        self._result += key + '="' + value + '" '

    self._result +=  ">"

  def _writeAndResetAdditionalData(self):
    self._result += self._additionalData
    self._additionalData = ""

  def handle_endtag(self, tag):
    self._writeAndResetAdditionalData ()
    self._result += "</" + tag + ">"


  def handle_data(self, data):
    self._result += data

  def run(self, content, basedir):
    self._baseDir = basedir
    self.feed (content)
    return self._result



def merge(strInfile, strOutfile):

  if (not os.path.isfile (strInfile)):
    print ("FATAL ERROR: file `" + strInfile + "` could not be accessed.")
    return

  baseDir = os.path.split (os.path.abspath (strInfile))[0]

  #read file
  content = getFileContent (strInfile)

  parser = HtmlMerger()
  content_changed = parser.run (content, baseDir)

  # log errors
  if (len (parser.messages) > 0):
    print ("Problems occured")
    for msg in parser.messages:
      print ("  " + msg)
    print ("")

  # debug:
  if (False):
    print (content_changed)
    exit ()


  # write result
  with open (strOutfile, "w") as file:
    file.write (content_changed)



def main():
  args = sys.argv[1:] # cut away pythonfile
  if (len (args) < 1):
    print (gHelp)
    exit()

  inputFile = args[0]

  # get output file name
  outputFile = ""
  if (True):
    outputFile = os.path.splitext (inputFile)[0] + "_merged.html"

    if (len (args) > 1):
      outputFile = args[1]

    if (os.path.isfile (outputFile)):
      print ("FATAL ERROR: Output file " + outputFile + " does already exist")
      exit ()

  # run the actual merge
  merge (inputFile, outputFile)


main()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接