Search code examples
webpackmodx

The right way to develop front-end/templates for MODx


I am working on integrating a template into MODx and stuck with trying to find the right way to deploy and update the assets.

I have a Webpack setup that compiles all my template files into static assets and HTML files which I planned to manually split in chunks and add as templates in MODx, but then I realized that those templates will be unmaintainable. Every change to an image, CSS, or JS will lead to content hash change, so the file names and URLs will also be changed.

There must be a way because almost every website today needs to pre-process images, compile CSS, use dynamic js imports, and so on, which is impossible without bundlers like Webpack.

So, what is the best practice for deploying and updating assets for MODx?


Solution

  • Finally, I came up with the following solution - I use the HTML Webpack Plugin with a custom EJS template to generate a file with all JS includes.

    <%
    for (key in htmlWebpackPlugin.files.chunks) { %><%
      if (htmlWebpackPlugin.files.jsIntegrity) { %>
    <script defer
      src="<%= htmlWebpackPlugin.files.chunks[key].entry %>"
      type="text/javascript"
      integrity="<%= htmlWebpackPlugin.files.jsIntegrity[htmlWebpackPlugin.files.js.indexOf(htmlWebpackPlugin.files.chunks[key].entry)] %>"
      crossorigin="<%= webpackConfig.output.crossOriginLoading %>"></script><%
      } else { %>
    <script defer src="<%= htmlWebpackPlugin.files.chunks[key].entry %>" type="text/javascript"></script><%
      } %><%
    } %>
    

    In ModX this file is used as a static source for a chunk that is inserted in the footer chuck. This allows to automatically update links to js assets on recompile. The same tactic is used for CSS assets.

    Unfortunately, there is no work-around for images, so you have to manually edit your ModX templates if you change a linked image.