【问题标题】:Python script for minifying CSS? [closed]用于缩小 CSS 的 Python 脚本? [关闭]
【发布时间】:2010-09-18 08:46:11
【问题描述】:

我正在寻找一个简单的 Python 脚本,它可以在网站部署过程中缩小 CSS。 (Python 是服务器上唯一支持的脚本语言,像 CSS Utils 这样成熟的解析器对于这个项目来说是多余的)。

基本上我希望 jsmin.py 用于 CSS。没有依赖关系的单个脚本。

有什么想法吗?

【问题讨论】:

    标签: python css compression minify


    【解决方案1】:

    这对我来说似乎是一个很好的任务来进入 python,它已经等待了一段时间。我在此展示我的第一个 python 脚本:

    import sys, re
    
    with open( sys.argv[1] , 'r' ) as f:
        css = f.read()
    
    # remove comments - this will break a lot of hacks :-P
    css = re.sub( r'\s*/\*\s*\*/', "$$HACK1$$", css ) # preserve IE<6 comment hack
    css = re.sub( r'/\*[\s\S]*?\*/', "", css )
    css = css.replace( "$$HACK1$$", '/**/' ) # preserve IE<6 comment hack
    
    # url() doesn't need quotes
    css = re.sub( r'url\((["\'])([^)]*)\1\)', r'url(\2)', css )
    
    # spaces may be safely collapsed as generated content will collapse them anyway
    css = re.sub( r'\s+', ' ', css )
    
    # shorten collapsable colors: #aabbcc to #abc
    css = re.sub( r'#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3(\s|;)', r'#\1\2\3\4', css )
    
    # fragment values can loose zeros
    css = re.sub( r':\s*0(\.\d+([cm]m|e[mx]|in|p[ctx]))\s*;', r':\1;', css )
    
    for rule in re.findall( r'([^{]+){([^}]*)}', css ):
    
        # we don't need spaces around operators
        selectors = [re.sub( r'(?<=[\[\(>+=])\s+|\s+(?=[=~^$*|>+\]\)])', r'', selector.strip() ) for selector in rule[0].split( ',' )]
    
        # order is important, but we still want to discard repetitions
        properties = {}
        porder = []
        for prop in re.findall( '(.*?):(.*?)(;|$)', rule[1] ):
            key = prop[0].strip().lower()
            if key not in porder: porder.append( key )
            properties[ key ] = prop[1].strip()
    
        # output rule if it contains any declarations
        if properties:
            print "%s{%s}" % ( ','.join( selectors ), ''.join(['%s:%s;' % (key, properties[key]) for key in porder])[:-1] ) 
    

    我相信这行得通,并且在最近的 Safari、Opera 和 Firefox 上测试良好。它将破坏除下划线和 /**/ hacks 之外的 CSS hacks!如果您有很多 hack 正在进行(或将它们放在单独的文件中),请不要使用 minifier。

    对我的 python 的任何提示表示赞赏。不过请温柔一点,我是第一次。 :-)

    【讨论】:

    • 您可以使用索引 -1 来引用序列中的最后一个元素。因此,您可以使用 .append() 而不是 .insert(),并避免使用 .reverse()。此外,如果 len(lst) > 0: 通常像 lst:
    • 感谢您的提示。我已经解决了这些问题和其他一些问题。 Python 是一门非常好的语言。 :-)
    • 干得好!小问题:“缩小”/* *//**/
    • 多年后.. 仍然有用 :) 现在是我构建过程的一部分
    • @AtesGoral 为什么会有这样的问题?
    【解决方案2】:

    webassets 文档中,您可以找到多个压缩器和编译器的链接。从该列表中,我选择了pyScss,它还缩小了生成的 CSS。

    如果你只需要一个 CSS 压缩器,你可以试试csscompressor

    几乎完全是 YUI CSS Compressor 的移植版。通过所有原始单元测试。

    更通用的工具是css-html-prettify

    StandAlone Async 单文件跨平台支持 Unicode 的 Python3 Prettifier Beautifier for the Web。

    【讨论】:

      【解决方案3】:

      如果有人遇到这个问题并且正在使用 Django,有一个常用的包来解决这个问题,称为Django Compressor

      将链接和内联的 JavaScript 或 CSS 压缩到单个缓存文件中。

      • JS/CSS 属于模板

      • 灵活性

      • 不碍事

      • 完整的测试套件

      【讨论】:

        【解决方案4】:

        有一个不错的在线工具cssminifier,它还有一个非常简单易用的API。 我制作了一个小型 python 脚本,将 CSS 文件内容发布到该工具的 API,返回缩小的 CSS 并将其保存到文件“style.min.css”中。我喜欢它,因为它是一个可以很好地集成到自动化部署脚本中的小代码:

        import requests
        f = open("style.css", "r")
        css_text = f.read()
        f.close()
        r = requests.post("http://cssminifier.com/raw", data={"input":css_text})
        css_minified = r.text
        f2 = open("style.min.css", "w")
        f2.write(css_minified)
        f2.close()
        

        【讨论】:

        • 来自 cssminifier 网站:cssminifier.com/python
        • 我遇到了错误,试图向 «http» 网址发送请求。 cssminifier.com 和 javascript-minifier.com 的 «https» url 工作正常。
        【解决方案5】:

        有一个 YUI 的 CSS 压缩器端口可用于 python。

        这是它在 PyPi 上的项目页面: http://pypi.python.org/pypi/cssmin/0.1.1

        【讨论】:

        【解决方案6】:

        我不知道任何现成的 python css 缩小器,但就像你说的 css utils 有选项。在检查并验证许可证是否允许之后,您可以浏览源代码并剪掉自己进行缩小的部分。然后将其粘贴在一个脚本中,瞧!给你。

        首先,.../trunk/src/cssutils/script.py 中的 csscombine 函数似乎可以在第 361 行附近进行缩小(我查看了修订版 1499)。请注意名为“minify”的布尔函数参数。

        【讨论】:

          猜你喜欢
          • 2012-04-12
          • 1970-01-01
          • 2014-10-10
          • 2011-11-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多