Search code examples
htmlflaskwebpackjinja2assets

Webpack, jinja templates and static paths


How do I integrate webpack loader/semi-filter into jinja templates? I want to transform a jinja template into a jinja template, but the static paths replaced with the output paths according to webpack config. Basically PUG-loader's require(), but for jinja.

Let's say the filter query would look like this: src="{{ 'path' | webpack }}", but it's not an actual jinja filter, since at build time it would be replaced with src='outputPath'. Where should I start looking at? HTMLWebpackPlugin? HTML-loader? Other jinja/flask/webpack related projects I looked at tend to bind webpack to flask server more rather than less, which isn't suited for my situation.


Solution

  • as I understood you are trying to put your static files into jinja template but with all stuff that webpack makes for you including hashes in files' names, i know only one solution for this:

    1. you should to firbid htmlWebpackPlugin to inject scripts in your template like this:

      new htmlWebpackPlugin(
          template: 'your/template/path',
          inject: false
      )
      
    2. then in your template use webpack's template to automaticly inject scripts:

      ...
      <script defer src = <%= `"{{url_for('static', filename ='${(htmlWebpackPlugin.js}).toString().split('/').pop()}')}}"` %>
      

    this method just inserts some js code into template, that does such injection for you, if you want more static files, just use the same method but with another js code

    read more about htmlWebpackPlugin