我正在寻找一个简单的 Python 脚本,它可以在网站部署过程中缩小 CSS。 (Python 是服务器上唯一支持的脚本语言,而像 CSS Utils 这样成熟的解析器对于这个元素来说是多余的)。
基本上我想要 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 上测试良好。它将破坏除下划线和/**/hacks 之外的 CSS hacks!如果您有很多 hack 正在进行(或将它们放在单独的文件中),请不要使用 minifier。
对我的 python 的任何提示表示赞赏。不过请温柔一点,我是第一次。 :-)
关于用于缩小 CSS 的 Python 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/222581/