Update for Latest Versions of Sphinx
Recent builds using the following solution are encountering failures with the error message:
Reason: ThemeError("Local asset file paths must not contain query strings: '_static/custom.css?v=12345678'")
Bug reports indicate that this issue has also affected builds in other major projects such as MathJax, NumPy, Gentoo, and Bokeh.
As per a comment by a contributor to Sphinx, the new approach involves Sphinx handling cache busting through a content checksum, eliminating the need for manual cache busting.
Version Compatibility for Older Sphinx Releases
Although the configuration file seems to only support standard string values, it is essentially a Python script allowing us to utilize functions like a random number generator.
Add the following line at the top of conf.py
:
from secrets import token_urlsafe
Modify your custom CSS + JS as follows:
html_css_files = [f'css/custom.css?v={token_urlsafe(8)[:8]}']
html_js_files = [f'js/custom.js?v={token_urlsafe(8)[:8]}']
This change will ensure that your custom CSS + JS files load similar to vanilla CSS + JS files, with an 8-character random slug appended at the end, thus preventing caching:
<!-- Vanilla CSS from Sphinx: -->
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
<link rel="stylesheet" type="text/css" href="../_static/css/theme.css?v=19f00094" />
<link rel="stylesheet" type="text/css" href="../_static/copybutton.css?v=76b2166b" />
<!-- Custom CSS now includes a random slug, similar to vanilla: -->
<link rel="stylesheet" type="text/css" href="../_static/css/custom.css?v=Rdy7RNCQ" />
<!-- Vanilla JS from Sphinx: -->
<script src="../_static/jquery.js?v=5d32c60e"></script>
<script src="../_static/_sphinx_javascript_frameworks_compat.js?v=2cd50e6c"></script>
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js?v=e91dff3d"></script>
<script src="../_static/doctools.js?v=888ff710"></script>
<script src="../_static/sphinx_highlight.js?v=4825356b"></script>
<script src="../_static/clipboard.min.js?v=a7894cd8"></script>
<script src="../_static/copybutton.js?v=f281be69"></script>
<!-- Custom JS now includes a random slug, similar to vanilla: -->
<script src="../_static/js/custom.js?v=8QronLhw"></script>
It's important to note that if you're using Sphinx within a Docker environment, the ?v=xxxxxxxx
slug may remain unchanged unless you utilize the --no-cache
option when running your docker build
.