0

Platform:

  1. Gatsby v2.28.0
  2. html-critical-webpack-plugin
  3. Webpack v4 pre-configured with Gatsby

Our requirement is to extract the CSS which is required above the fold in mobile and desktop. Then the plugin would programmatically insert the extracted CSS into the final built HTML file as an inline style in the head thereby reducing the initial network load and the CSS-rendering blocking files would be reduced, increasing the performance scores.

Since webpack is pre-configured in Gatsby, we use the above plugin in conjunction with Gatsby's onPostBuild function so that after the HTML file has been built and sent out to the public folder, we need to do the extraction of CSS and push it in the HTML file.

Tried:

exports.onPostBuild = ({ reporter, basePath, pathPrefix }) => {
  const path1 = path.join(__dirname, '../', 'web', 'public', 'index.html');
  reporter.info(
    `Site was built with basePath: ${basePath} & pathPrefix: ${pathPrefix} and index.html ${path1} PATH.`
  );

new HtmlCriticalWebpackPlugin({
    base: path.join(__dirname, 'web', 'public'),
    src: 'index.html',
    dest: 'index.html',
    inline: true,
    minify: true,
    extract: true,
    width: 375,
    height: 565,
    penthouse: {
      blockJSRequests: false,
    },
  });

  const logStream = fs.createWriteStream(path1, { flags: 'a' });
  // use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
  logStream.write('Initial line...');
  logStream.end('this is the end line');
};

The path is correctly pointing to the HTML file in the public directory which is available after the production build completes and the onPostBuild function runs at the very end of the build process.

I have tried to log some dummy data to the HTML file at that works fine. We do not have any permission issues for write.

Expected:

enter image description here

Above the fold CSS should be programmatically extracted from the styles.hash.css file and inline in HTML.

invinciblemuffi
  • 908
  • 1
  • 11
  • 22

0 Answers0