Django中使用django-compressor压缩混淆静态文件

526 阅读1分钟

前言

使用django-compressor可以压缩django模板中的js/css文件,有利于减少网站的请求次数和节省网络带宽,下面介绍如何在django中使用django-compressor

安装

pip install django-compressor

使用

  1. settingsINSTALLED_APPS中添加compressor
    INSTALLED_APPS = [
        '...',
        'compressor',
    ]
    
  2. 设置STATIC_ROOT
  3. 设置compressor相关配置
    COMPRESS_ENABLED = True
    COMPRESS_OFFLINE = True
    
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'compressor.finders.CompressorFinder',
    )
    
  4. 在模板中使用
    {% load compress %}
    
    {% compress css %}
    <link rel="stylesheet" href="{% static 'css/ex.css' %}">
    {% endcompress %}
    
    {% compress js %}
    <link rel="stylesheet" href="{% static 'js/ex.js' %}">
    {% endcompress %}
    
  5. 生成cache文件
    python manage.py compress
    
  6. 最后就可以在STATIC_ROOT看见会创建一个CACHE目录生成的压缩混淆文件了