Bạn có thể sử dụng trình chỉnh sửa google js. Dưới đây là một kịch bản python trong đó sử dụng nó để nén một loạt các file javascript với nó:
import httplib
import simplejson as json
import urllib
import sys
def combine_js(js_files, minify=False):
files = list(js_files) # create a copy which we can modify
if not minify:
code = []
for path in files:
f = open(path, 'r')
code.append(f.read())
f.close()
return '\n\n'.join(code)
def _minify(code):
params = urllib.urlencode([
('js_code', code),
('compilation_level', 'SIMPLE_OPTIMIZATIONS'),
('output_format', 'json'),
('output_info', 'compiled_code'),
('output_info', 'errors'),
('output_info', 'warnings'),
])
headers = {'Content-type': "application/x-www-form-urlencoded"}
conn = httplib.HTTPConnection('closure-compiler.appspot.com')
conn.request('POST', '/compile', params, headers)
response = conn.getresponse()
data = json.loads(response.read())
conn.close()
if not data.get('compiledCode'):
print >>sys.stderr, 'WARNING: Did not get any code from google js compiler.'
print >>sys.stderr, data
print >>sys.stderr
print >>sys.stderr, 'Using unminified code'
return None
return data.get('compiledCode')
# Minify code in chunks to avoid the size limit
chunks = []
code = ''
while len(files):
path = files[0]
f = open(path, 'r')
data = f.read()
f.close()
# Check if we reach the size limit
if len(code + data) >= 1000000:
res = _minify(code)
if res is None:
# Fallback to unminified code
return combine_js(js_files)
chunks.append(res)
code = ''
continue
code += data
del files[0]
if code:
res = _minify(code)
if res is None:
# Fallback to unminified code
return combine_js(js_files)
chunks.append(res)
return '\n\n'.join(chunks).strip()
if __name__ == '__main__':
print combine_js(sys.argv[1:], True)
Cách sử dụng: python filename.py path/to/your/*.js > minified.js
Trong trường hợp bạn đang sử dụng một phiên bản python cổ và không có simplejson cài đặt trên hệ thống của bạn, dưới đây là cách bạn có thể làm cho tập lệnh hoạt động với phiên bản simplejson cục bộ (chạy các lệnh đó qua SSH):
cd
wget http://pypi.python.org/packages/source/s/simplejson/simplejson-2.3.2.tar.gz
tar xzf simplejson-2.3.2.tar.gz
export PYTHONPATH=$HOME/simplejson-2.3.2/
Bạn đã cân nhắc việc rút gọn một nơi khác e tải lên máy chủ của bạn? – jergason
Có lẽ cách dễ nhất là sử dụng dịch vụ web cho việc này bằng cách sử dụng cURL hoặc tương tự – Vitamin
@Jergason: Không thể sử dụng git cho dự án của tôi. – qwertymk