<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Øystein Amundsen on Medium]]></title>
        <description><![CDATA[Stories by Øystein Amundsen on Medium]]></description>
        <link>https://medium.com/@oysteinamundsen?source=rss-10c22eb818d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cFVv9qpCHrWnqGo3JCADJw.jpeg</url>
            <title>Stories by Øystein Amundsen on Medium</title>
            <link>https://medium.com/@oysteinamundsen?source=rss-10c22eb818d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:52:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oysteinamundsen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Adding Workbox to an Angular App in an NX Workspace]]></title>
            <link>https://blog.stackademic.com/adding-workbox-to-an-angular-app-in-an-nx-workspace-111b5ac040fa?source=rss-10c22eb818d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/111b5ac040fa</guid>
            <category><![CDATA[workbox]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[service-worker]]></category>
            <dc:creator><![CDATA[Øystein Amundsen]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 07:44:40 GMT</pubDate>
            <atom:updated>2023-10-04T01:29:57.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Workbox is a fantastic tool, but it is rather hard to find good examples of how to implement it properly in frameworks like angular. I had a hard time finding enough information on this subject, so in the interest of sharing, I thought I might try to put this in here.</p><p>Down to business. Firstly, this is my directory structure, and the files I will go through in this article:</p><pre>apps<br>  ⨽ myApp<br>    ⨽ src<br>      ⊦ ngsw-worker.ts  ← My Workbox SW template<br>      ⊦ main.ts         ← The applications main entry point<br>    ⊦ tsconfig.wb.json  ← Only needed for the extra webpack build step<br>    ⊦ webpack.config.js ← Config of the extra build step<br>    ⊦ project.json      ← NX version of the angular cli config<br>  dist<br>  ⨽ apps<br>    ⨽ myApp</pre><h3>project.json</h3><p>First up is the changes I made to my <em>project.json</em> file (<em>this is the NX equivilant of angular.json</em>). Since there is no built in way to add files from the build process into my manifest of precached files, I had to switch out the default angular builder with a custom webpack builder:</p><blockquote>Note that the following is not my complete project.json file. Only the parts to make the build recognize my custom webpack config. If you do not have a project.json file, look for an angular.json file. It should work somewhat the same way.</blockquote><pre>{<br>  &quot;name&quot;: &quot;myApp&quot;,<br>  ...<br>  &quot;targets&quot;: {<br>    &quot;build&quot;: {<br>      &quot;executor&quot;: &quot;@angular-builders/custom-webpack:browser&quot;,<br>      ...<br>      &quot;options&quot;: {<br>        &quot;customWebpackConfig&quot;: {<br>          &quot;path&quot;: &quot;apps/myApp/webpack.config.js&quot;,<br>          &quot;replaceDuplicatePlugins&quot;: true<br>        },<br>      },<br>      ...<br>    },<br>    &quot;serve&quot;: {<br>      &quot;executor&quot;: &quot;@angular-builders/custom-webpack:dev-server&quot;,<br>      ...<br>    }<br>  },<br>}</pre><h3>webpack.config.js</h3><p>And then we have our custom webpack config. This is executed during the build sometime after angular has done it’s bit and compiled all resources, but apparently before angular copies assets and such. That’s why I have to copy all assets I want to be in the precache before I run <em>InjectManifest</em>.</p><pre>const path = require(&#39;path&#39;);<br>const { InjectManifest } = require(&#39;workbox-webpack-plugin&#39;);<br>const CopyPlugin = require(&#39;copy-webpack-plugin&#39;);<br>const AngularWebpackPlugin = require(&#39;@ngtools/webpack&#39;).AngularWebpackPlugin;<br><br>module.exports = {<br>  plugins: [<br>    // Required to get InjectManifest to precache assets, since this webpack config<br>    // apparently runs before angular copies assets to dist.<br>    new CopyPlugin({<br>      patterns: [<br>        { context: &#39;apps/myApp/src&#39;, from: &#39;**/index.html&#39;, to: &#39;./&#39; },<br>        { context: &#39;apps/myApp/src/.root/&#39;, from: &#39;**/*&#39;, to: &#39;./&#39; },<br>      ],<br>    }),<br>    new InjectManifest({<br>      swSrc: path.resolve(__dirname, &#39;./src/ngsw-worker.ts&#39;),<br>      swDest: path.resolve(__dirname, &#39;../../dist/apps/myApp/ngsw-worker.js&#39;),<br>      // Allows the plugin to compile the ngsw-worker.ts file<br>      compileSrc: true,<br>      webpackCompilationPlugins: [<br>        // Without this, Webpack yields an error.<br>        // The only reason for having a separate tsconfig here, is to add<br>        // a different `files` array. If I include the ngsw-worker.ts file in the main<br>        // tsconfig, angular gives complains a lot.<br>        new AngularWebpackPlugin({ tsconfig: &#39;apps/myApp/tsconfig.wb.json&#39; }),<br>      ],<br>      // injectionPoint: &#39;self.__WB_MANIFEST&#39;,<br>      exclude: [/\-es5.js$/, /\.(js|css)\.map$/],<br>      // Allows to avoid using cache busting for Angular files because Angular already takes care of that!<br>      dontCacheBustURLsMatching: new RegExp(&#39;.+.[a-f0-9]{20}..+&#39;),<br>      maximumFileSizeToCacheInBytes: 10 * 1024 * 1024, // 10MB<br>    }),<br>  ],<br>};</pre><p>I tried using other typescript compilers here, but since this is run side-by-side with the angular compilation, other compilers than the <em>AngularWebpackPlugin</em> will throw an error.</p><h3>tsconfig.wb.json</h3><p>The tsconfig.wb.json is a clone of the tsconfig.app.json file, where only the files array is changed. I need to input the entry file which is to be compiled:</p><pre>{<br>  ...<br>  &quot;files&quot;: [&quot;src/ngsw-worker.ts&quot;],<br>}</pre><p>Ok, so I have my build process set up. The only thing I need to build and run my application, is to execute:</p><pre>npm start myApp</pre><p>Now for the actual service worker:</p><h3>ngsw-worker.ts</h3><p>You might wonder about the name. You see I migrated from @angular/service-worker. The output from the standard build is a file called ngsw-worker.js and changing the url of a service-worker after users has installed it, <a href="https://web.dev/service-worker-lifecycle/#avoid-url-change">is a bad idea</a>.</p><pre>import { CacheableResponsePlugin } from &#39;workbox-cacheable-response&#39;;<br>import { clientsClaim, setCacheNameDetails } from &#39;workbox-core&#39;;<br>import { ExpirationPlugin } from &#39;workbox-expiration&#39;;<br>import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from &#39;workbox-precaching&#39;;<br>import { registerRoute } from &#39;workbox-routing&#39;;<br>import { CacheFirst, NetworkFirst } from &#39;workbox-strategies&#39;;<br><br>declare const self: ServiceWorkerGlobalScope | any;<br>const prefix = &#39;myApp&#39;;<br>const version = &#39;v2&#39;;<br><br>/**<br> * The workboxSW.precacheAndRoute() method efficiently caches and responds to<br> * requests for URLs in the manifest.<br> * See https://goo.gl/S9QRab<br> */<br>setCacheNameDetails({<br>  prefix: prefix,<br>  suffix: version,<br>  precache: &#39;precache&#39;,<br>});<br>const manifest = self.__WB_MANIFEST;<br>precacheAndRoute(manifest);<br><br>// Set up App Shell-style routing, so that all navigation requests<br>// are fulfilled with your index.html shell. Learn more at<br>// https://developers.google.com/web/fundamentals/architecture/app-shell<br>const fileExtensionRegexp = new RegExp(&#39;/[^/?]+\\.[^/]+$&#39;);<br>registerRoute(<br>  // Return false to exempt requests from being fulfilled by index.html.<br>  ({ request, url }) =&gt; {<br>    // If this isn&#39;t a navigation, skip.<br>    if (request.mode !== &#39;navigate&#39;) return false;<br><br>    // If this looks like a URL for a resource, because it contains <br>    // a file extension, skip.<br>    if (url.pathname.match(fileExtensionRegexp)) return false;<br><br>    // Return true to signal that we want to use the handler.<br>    return true;<br>  },<br>  createHandlerBoundToURL(&#39;/index.html&#39;),<br>);<br><br>/**<br> * -------------------------------------------------------<br> * Define cache strategy and routes here<br> * -------------------------------------------------------<br> */<br>// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.<br>registerRoute(<br>  /^https:\/\/fonts\.googleapis\.com/,<br>  new CacheFirst({<br>    cacheName: `${prefix}-fontstylesheet-${version}`,<br>    plugins: [<br>      new CacheableResponsePlugin({ statuses: [200] }),<br>      new ExpirationPlugin({ maxAgeSeconds: 60 * 60 * 24 * 365 }),<br>    ],<br>  }),<br>);<br><br>// Cache the underlying font files with a cache-fist strategy for 1 year.<br>registerRoute(<br>  /^https:\/\/fonts\.gstatic\.com/,<br>  new CacheFirst({<br>    cacheName: `${prefix}-fonts-${version}`,<br>    plugins: [<br>      new CacheableResponsePlugin({ statuses: [200] }),<br>      new ExpirationPlugin({ maxAgeSeconds: 60 * 60 * 24 * 365 }),<br>    ],<br>  }),<br>);<br><br>//cache any external images for 30 days<br>registerRoute(<br>  /\.(png|gif|jpg|jpeg|svg|ico)$/,<br>  new CacheFirst({<br>    cacheName: `${prefix}-images-${version}`,<br>    plugins: [<br>      new CacheableResponsePlugin({ statuses: [200] }),<br>      new ExpirationPlugin({ maxEntries: 200, maxAgeSeconds: 60 * 60 * 24 * 30 }),<br>    ],<br>  }),<br>);<br><br>// cache the data request so that, if the network is off we get the last good response<br>registerRoute(<br>  ({ url }) =&gt; url.pathname.startsWith(&#39;/api/&#39;),<br>  new NetworkFirst({<br>    cacheName: `${prefix}-api-${version}`,<br>    plugins: [<br>      new CacheableResponsePlugin({ statuses: [200] }),<br>      new ExpirationPlugin({ maxAgeSeconds: 60 * 60 * 24 * 1 }),<br>    ],<br>  }),<br>  &#39;GET&#39;,<br>);<br>/**<br> * -------------------------------------------------------<br> * End of cache strategy and routes<br> * -------------------------------------------------------<br> */<br><br>// Install app immediately when client is ready<br>self.addEventListener(&#39;message&#39;, (event: MessageEvent) =&gt; {<br>  if (event.data &amp;&amp; event.data.type === &#39;SKIP_WAITING&#39;) {<br>    self.skipWaiting();<br>    clientsClaim();<br>    cleanupOutdatedCaches();<br>  }<br>});</pre><h3>main.ts</h3><p>And on the client I do the setup in my main.ts file:</p><pre>import { enableProdMode } from &#39;@angular/core&#39;;<br>import { bootstrapApplication } from &#39;@angular/platform-browser&#39;;<br>import { platformBrowserDynamic } from &#39;@angular/platform-browser-dynamic&#39;;<br>import { Workbox } from &#39;workbox-window&#39;;<br><br>import { AppModule } from &#39;./app/app.module&#39;;<br>import { environment } from &#39;./environments/environment&#39;;<br><br>if (environment.production) {<br>  enableProdMode();<br>}<br><br>platformBrowserDynamic()<br>  .bootstrapModule(AppModule)<br>  .then(() =&gt; loadServiceWorker())<br>  .catch(err =&gt; console.error(err));<br><br>/**<br> * Load service worker<br> * This will also listen for updates and act accordingly<br> */<br>async function loadServiceWorker() {<br>  if (&#39;serviceWorker&#39; in navigator) {<br>    try {<br>      const wb = new Workbox(&#39;/ngsw-worker.js&#39;, { scope: &#39;/&#39; });<br>      wb.addEventListener(&#39;waiting&#39;, () =&gt; wb.messageSkipWaiting());<br>      wb.addEventListener(&#39;controlling&#39;, () =&gt; window.location.reload());<br>      const reg = await wb.register({ immediate: true });<br>      if (!reg) throw &#39;Service worker not registered!&#39;;<br><br>      // Check for updates every 5 minutes<br>      setInterval(() =&gt; wb.update(), 5 * 60 * 1000);<br>    } catch (err) {<br>      // Registration failed :(<br>      console.error(&#39;Service worker registration failed!&#39;, err);<br>    }<br>  }<br>}</pre><p>That’s it. You now have a service-worker running in your angular app.</p><p>This setup will force new versions onto the client as soon as they are available on the server. If you do not want this, edit the <em>‘controlling’</em> event listener in the <em>main.ts</em> file and add in a user interaction before <em>window.location.reload()</em>.</p><p>I hope this can help others.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=111b5ac040fa" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/adding-workbox-to-an-angular-app-in-an-nx-workspace-111b5ac040fa">Adding Workbox to an Angular App in an NX Workspace</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>