Skip to content

Commit

Permalink
docs(router): add guide on using postrenderhooks (#773)
Browse files Browse the repository at this point in the history
Co-authored-by: Ajit Panigrahi <[email protected]>
  • Loading branch information
santoshyadavdev and ajitzero authored Dec 4, 2023
1 parent 608780a commit 07452e0
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions apps/docs-app/docs/features/server/static-site-generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,83 @@ mapping of the pages' `<loc>` and `<lastmod>` properties.
</url>
</urlset...>
```

### Post-rendering Hooks

Analog supports the post-rendering hooks during the prerendering process. The use case for post-rendering hooks can be inlining critical CSS, adding/removing scripts in HTML files, etc.

The sample code below shows how to use `postRenderingHooks` in your code:

```ts
import analog from '@analogjs/platform';
import { defineConfig } from 'vite';
import { PrerenderRoute } from 'nitropack';

// https://vitejs.dev/config/
export default defineConfig(() => {
return {
publicDir: 'src/public',
build: {
target: ['es2020'],
},
plugins: [
analog({
static: true,
prerender: {
routes: async () => [],
postRenderingHooks: [
async (route: PrerenderRoute) => console.log(route),
],
},
}),
],
};
});
```

The `PrerenderRoute` gives you information about `route`, `contents`, `data`, and `fileName`, which can be useful for making changes to your content during the prerendering phase.

Below is a small example where we can append a script to include Google Analytics during the prerendering process using `postRenderingHooks`:

```ts
/// <reference types="vitest" />

import analog from '@analogjs/platform';
import { defineConfig, splitVendorChunkPlugin } from 'vite';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
import { PrerenderRoute } from 'nitropack';

// https://vitejs.dev/config/
export default defineConfig(() => {
return {
publicDir: 'src/public',
build: {
target: ['es2020'],
},
plugins: [
analog({
static: true,
prerender: {
routes: async () => ['/', '/aboutus'],
postRenderingHooks: [
async (route: PrerenderRoute) => {
const gTag = `<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxxxx-1', 'auto');
ga('send', 'pageview');
</script>`;
if (route.route === '/aboutus') {
route.contents = route.contents?.concat(gTag);
}
},
],
},
}),
],
};
});
```

0 comments on commit 07452e0

Please sign in to comment.