Flask-Assets 基于 ​​webassets​​​,个人感觉是Python版的​​webpack​

安装

pip install Flask-Assets

使用示例

目录结构

.
├── __init__.py
├── run.py # 入口文件
├── static
│ ├── css
│ │ ├── common-1.css
│ │ ├── common-2.css
│ │ └── common.css # 打包后的css文件
│ └── js
│ ├── common-1.js
│ ├── common-2.js
│ └── common.js # 打包后的js文件
└── templates
└── index.html

run.py

# -*- coding: utf-8 -*-

from flask import Flask, render_template
from flask_assets import Environment, Bundle

app = Flask(__name__)

# 调试环境不打包
app.config['ASSETS_DEBUG'] = True

# 打包配置
assets_env = Environment(app)

common_js = Bundle(
'js/common-1.js',
'js/common-2.js',
filters='jsmin',
output='js/common.js')

common_css = Bundle(
'css/common-1.css',
'css/common-2.css',
filters='cssmin',
output='css/common.css')

# 注册打包文件
assets_env.register('common_js', common_js)
assets_env.register('common_css', common_css)


# 路由
@app.route('/')
def hello_world():
return render_template('index.html')


if __name__ == '__main__':
app.run(debug=True)

static/css/common-1.css

.box-1{
color: red;
}

static/css/common-2.css

.box-2{
color: grey;
}

static/js/common-1.js

function foo1() {

}

static/js/common-2.js

function foo2() {

}

templates/index.html

{% assets "common_js" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}

{% assets "common_css" %}
<link rel="stylesheet" type="text/css" href="{{ ASSET_URL }}" />
{% endassets %}

输出

​http://127.0.0.1:5000/​

ASSETS_DEBUG=True

<script type="text/javascript" src="/static/js/common-1.js"></script>

<script type="text/javascript" src="/static/js/common-2.js"></script>


<link rel="stylesheet" type="text/css" href="/static/css/common-1.css" />

<link rel="stylesheet" type="text/css" href="/static/css/common-2.css" />

ASSETS_DEBUG=False

<script type="text/javascript" src="/static/js/common.js?207d589d"></script>

<link rel="stylesheet" type="text/css" href="/static/css/common.css?30e0ca9e" />

/static/css/common.css

.box-1{color:red}.box-2{color:grey}

/static/js/common.js

function foo1(){}
function foo2(){}


参考
flask assets压缩静态文件(flask 111)