Bill Barry
Bill Barry

Reputation: 3543

Angular 12: How can I add a custom compiled script to build output chunks?

We need to deploy a custom service worker (NOT the Angular Service Worker) with our application and want to write it within the application so we can do something like:

///... app.module.ts... simplified to get the idea
function registerServiceWorker() {
  if ('serviceWorker' in navigator) {
    // here I have the first problem: this filename is the file in my source
    navigator.serviceWorker.register('./service-worker.ts', {scope: `/${enviroment.BASE_PATH}/sw-test/`});
  }
}

@NgModule({
  //...
  providers: [{
      provide: APP_INITIALIZER,
      useFactory: registerServiceWorker,
      multi: true,
    },
  ]
})
public class AppModule {}
// ./service-worker.ts
// again this is a simplified example; it is a ts file because we are importing other ts files 
// like the environment file which is replaced by the correct version as part of the angular build
self.addEventListener('fetch', function(event) {
  event.respondWith(Promise.resolve('example').then(function (text){
    return new Response(text, { headers: {'Content-Type': 'text/plain' }});
  }));
});

And we are having a problem: this second file doesn't get included in our build and the string to register doesn't get updated with a .js file from an output build directory...

I was thinking if I could force the compiled output to be a specific name I could do something like:

navigator.serviceWorker.register(`/${enviroment.BASE_PATH}/service-worker.js`, {scope: `/${enviroment.BASE_PATH}/sw-test/`});

but there doesn't seem to be any way to trigger angular to build a particular named chunk that I can figure out. Is this possible or is there some custom builder that already exists to do this or documentation on how to write something?

Upvotes: 2

Views: 357

Answers (1)

Dinesh
Dinesh

Reputation: 1820

Have you tried adding your script to angular.json?

angular.json


"assets": [
  "src/favicon.ico",
  "src/assets"
  "src/service-worker.js"    <------<<<
]

Upvotes: 0

Related Questions