{% compress %} 標籤包裹現有 <link>/<script>。DEBUG=True 時原樣輸出,False 時自動合併、壓縮、指紋化、寫入 STATIC_ROOT。pip install django-compressor
# settings.py INSTALLED_APPS += ['compressor'] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') COMPRESS_ENABLED = not DEBUG # 生產環境自動啟用 COMPRESS_OFFLINE = True # 收集靜態文件時預編譯,避免首請求延遲
{% load compress %}
{% compress css %}
{% endcompress %}
{% compress js %}
{% endcompress %}
生產環境輸出:
python manage.py collectstatic --noinput python manage.py compress --force
生成 CACHE 目錄下的壓縮文件與 manifest,Nginx/CDN 直接服務靜態資源,**無需運行時壓縮**。
COMPRESS_PRECOMPILERS = (
('text/coffeescript', 'coffee --compile --stdio'),
('text/less', 'lessc {infile} {outfile}'),
('text/x-sass', 'sass {infile} {outfile}'),
('text/x-scss', 'sass --scss {infile} {outfile}'),
)
模板中指定類型:
{% compress css %}
{% endcompress %}
DEBUG = FalseALLOWED_HOSTS 配置正確collectstatic + compresslocation /static/ { expires 1y; add_header Cache-Control "public"; }STATIC_URL,啟用 Gzip/Brotli。| 現象 | 原因 | 解決 |
|---|---|---|
| 壓縮後文件 404 | STATIC_ROOT 未收集、Nginx 路徑錯誤 | 檢查 collectstatic 輸出目錄、Nginx root 指向 |
| Less/Coffee 報錯 | 節點環境缺失 lessc/coffee 命令 | 安裝 Node.js + npm install -g less coffee-script |
| 開發環境也壓縮 | COMPRESS_ENABLED 未綁定 DEBUG | 設 COMPRESS_ENABLED = not DEBUG |
| 模板語法錯誤 | 未 {% load compress %} | 每個使用壓縮的模板頂部必須載入 |