kumorig
6/8/2018 - 7:14 AM

htmlWebpack-template to generate two separate files (styles.html and scripts.html) to be included in wordpress header/footer (or similar).

htmlWebpack-template to generate two separate files (styles.html and scripts.html) to be included in wordpress header/footer (or similar).

const criticalCSS = new ExtractTextPlugin({filename: 'above-the-fold.css'});
const stylesCSS = new ExtractTextPlugin({filename: 'styles.[hash].css'});
const HtmlWebpackPlugin = require('html-webpack-plugin');
const extractLoaders = { use: [{ loader: 'css-loader', options: {minimize: true}}, 'sass-loader'] };
...

rules: [
    { // Above the fold
    test: /above-the-fold\.scss$/,
    use: criticalCSS.extract(extractLoaders)
  },
      
  { // Everything else
    test: /\.scss$/,
    exclude: /above-the-fold\.scss$/,
    use: stylesCSS.extract(extractLoaders)
  },
],

plugins:[
  stylesCSS,
  criticalCSS,
  new HtmlWebpackPlugin({ filename: 'styles.html', template: 'styles.ejs', inject: false }),
  new HtmlWebpackPlugin({ filename: 'scripts.html', template: 'scripts.ejs', inject: false }),
]
<!-- CSS -->
<% for (var i in htmlWebpackPlugin.files.css) { %>
  <% if (htmlWebpackPlugin.files.css[i] === '/above-the-fold.css'){ continue; } %>
  <link href="<%= htmlWebpackPlugin.files.css[i] %>" rel="stylesheet"> <% } %>
  
<!-- Inline CSS -->
<style><%= compilation.assets['above-the-fold.css'].source() %></style>
<!-- Scripts (ejs) -->
<% for (var i in htmlWebpackPlugin.files.js) { %>
<script src="<%= htmlWebpackPlugin.files.js[i] %>"></script><% } %>