当模板具有内联 JS 时缩小 Flask 应用程序?

rub*_*lex 5 python minify flask bundling-and-minification

部署应用程序之前的常规约定是缩小所有资产(css、html、js)。这通常假设所有资产都在一个独立的文件中(即所有 js 代码都在/js/mycode.js.

但是,我编写了一堆带有<script>标签的 jinja2 模板,它们使用了模板的变量。这对于快速快速编写 UI 很有用,但我想知道将所有这些迁移到一个 js 文件中以便以后可以进行缩小的最佳方法是什么?

例如,我有很多包含内联 js 的模板:

<div class="some_content">
    <button>{{mytext}}</button>
</div>
<script>
    $(".some_content button").click(function() {
        $(this).text("{{new_text}}");
        $.post("{{url_for('doit', name=name)}}", function() {
            console.log('Done!');
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

我知道我可以将 js 代码填充到一个文件中,然后执行{% include 'mycode.js' %},但随后我会将所有 js 代码导入到模板中。一些模板具有继承性,因此执行 include 语句会导致文件多次将整个脚本加载到页面中(不好)。而且我不确定包含这样的脚本如何与缩小一起工作。

有没有一种好方法可以将所有内联 JS 代码移动到外部文件,而不会失去 jinja2 模板变量的好处,以便我可以缩小我的 javascript?或者更确切地说,缩小所有内联 JS 的好方法是什么?

duf*_*ffn 5

您可以为此使用 jinja-assets-compressor。

https://github.com/jaysonsantos/jinja-assets-compressor

应用程序

from jac.contrib.flask import JAC
from flask import Flask, render_template
import jinja2
from jac import CompressorExtension

app = Flask(__name__)
app.config['COMPRESSOR_DEBUG'] = app.config.get('DEBUG')
app.config['COMPRESSOR_OUTPUT_DIR'] = './static'
app.config['COMPRESSOR_STATIC_PREFIX'] = '/static'
jac = JAC(app)

env = jinja2.Environment(extensions=[CompressorExtension])
env.compressor_output_dir = './static'
env.compressor_static_prefix = '/static'
env.compressor_source_dirs = './static_files'


@app.route("/")
def hello():
    return render_template('index.html', name='rublex')

if __name__ == "__main__":
    app.run()
Run Code Online (Sandbox Code Playgroud)

索引.html

<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Flask test</title>
    </head>
    <body>
      <h1>Hello World</h1>
      <button onclick="sayHi()">Say Hi</button>

        {% compress 'js' %}
        <script>
            function sayHi() {
              alert('{{ name }}');
            }
        </script>
        {% endcompress %}
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

输出JS

<script type="text/javascript" src="/static/62280e86f267fdbbd0cd10bb7b5ae3dc.js"></script>

function sayHi(){alert('rublex');}
Run Code Online (Sandbox Code Playgroud)