HtmlWebpackPlugin - inject js in body at a specifc place

koseduhemak picture koseduhemak · Mar 11, 2019 · Viewed 7.7k times · Source

I am using HtmlWebpackPlugin to inject javascript into my template file:

<html>
    ...
    <body>
        ...
        <?php echo $this->inlineScript(); ?>
        <script type="text/javascript" src="/dist/vendor.js?a4212b4b10c2d4d2d73e"></script>
    </body>
</html>

However, I need the generated bundle to be injected before the PHP code <?php echo $this->inlineScript(); ?>, to let inline scripts work properly (they require JQuery, which will be loaded inside vendor.js).

Result should be:

<html>
    ...
    <body>
        ...
        <script type="text/javascript" src="/dist/vendor.js?a4212b4b10c2d4d2d73e"></script>
        <?php echo $this->inlineScript(); ?>
    </body>
</html>

Is there a way to achieve this? Maybe it is possible to use a placeholder like <%= htmlWebpackPlugin.options.??? %> or something similar? If it does not work with HtmlWebpackPlugin, is there another webpack plugin I can use?

Answer

koseduhemak picture koseduhemak · Mar 11, 2019

Ok I figured it out. Put the following code where you want to include your js files:

<% for(var i=0; i < htmlWebpackPlugin.files.js.length; i++) {%>
    <script type="text/javascript" src="<%= htmlWebpackPlugin.files.js[i] %>"></script>
<% } %>

and set inject in HtmlWebpackPlugin options to false.

Keep in mind that you need to inject other stuff (css, meta tags, etc.) by hand, too. F.e. CSS:

<% for(var i=0; i < htmlWebpackPlugin.files.css.length; i++) {%>
    <link type="text/css" rel="stylesheet" href="<%= htmlWebpackPlugin.files.css[i] %>">
<% } %>