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

基本上我想要 jsmin.py 对于CSS。没有依赖关系的单个脚本。

有任何想法吗?

有帮助吗?

解决方案

这对我来说似乎是一个很好的任务,进入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上输出测试。它将打破除了下划线和放大器之外的CSS黑客攻击。 / ** /黑客!如果您正在进行大量黑客攻击(或将它们放在单独的文件中),请不要使用缩放器。

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

其他提示

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

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

如果有人遇到这个问题并且正在使用 Django,有一个常用的包用于解决这个问题,称为 姜戈压缩器:

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

  • JS/CSS 属于模板

  • 灵活性

  • 它不会妨碍你

  • 完整的测试套件

我不知道任何现成的python css minifiers,但是就像你说css utils有选项。在检查并验证许可证允许的情况下,您可以浏览源代码并剪掉自己进行缩小的部分。然后把它粘在一个脚本中瞧!你去吧。

作为一个先行者,... / trunk / src / cssutils / script.py中的csscombine函数似乎在第361行(我检查了修订版1499)的某处进行了缩小工作。请注意名为“minify”的布尔函数参数。

有一个很好的在线工具 cssminifier ,它还有一个非常简单易用的API。 我制作了一个小的python脚本,将CSS文件内容发布到该工具的API,返回minifed 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()

网络集文档中,您可以找到多个链接压缩机和编译器。从该列表中我选择了 pyScss ,这也缩小了生成的CSS。

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

  

YUI CSS Compressor的几乎准确的端口。通过所有原始的单元测试。

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

  

StandAlone异步单文件跨平台Unicode-ready Python3 Prettifier Beautifier for the Web。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top