I am using webpack 5 with HtmlWebpackPlugin
to build my frontend SPA.
I need to add nonce
attribute to <script ...
tags injected by HtmlWebpackPlugin
.
How do I do it?
Extra question: after that I am using this pages as Thymeleaf templates before serving. How do I inject nonce
value?
If you were using webpack 4, there is plenty of fish in the sea — just use any plugin which injects attributes, such as script-ext-html-webpack-plugin or html-webpack-inject-attributes-plugin
However, most of the plugins mentioned above do not work with webpack 5. The workaround is to use the HtmlWebpackPlugin
templates.
inject
to false
in HtmlWebpackPlugin
options specified in webpack.config
. <% for (key in htmlWebpackPlugin.files.js) { %>
<script type="text/javascript" defer="defer" src="<%= htmlWebpackPlugin.files.js[key] %>"></script>
<% } %>
script
. Thymeleaf example: <% for (key in htmlWebpackPlugin.files.js) { %>
<script type="text/javascript" defer="defer" th:attr="nonce=${cspNonce}" src="<%= htmlWebpackPlugin.files.js[key] %>"></script>
<% } %>
Answer based on github post