Webpack and Web Workers in ionic 2

We plan on using web workers in ionic app 2. However, ionic 2 uses ionic scripts ( https://github.com/ionic-team/ionic-app-scripts , we're using version 1.0.0) with webpack. We need a webworker typescript file that is compiled to JS but NOT linked to other files like main.js.

What we meant is to have a filename format like

servicetest.worker.ts where part of the .worker file extension will be identified and compiled from typescript to javascript, but not linked together with other files.

Any advice on this is greatly appreciated as it seems like we need to tweak the application scripts.

+3


source to share


1 answer


Kind of really late answer, but maybe it could help someone else. Take a look at https://www.javascripttuts.com/how-to-use-web-workers-with-ionic-in-one-go/

I followed this article, but I had to make some adjustments because I had to call the working method on demand, not the constructor.

In the folder, ./src/assets

create a new folder called workers where your workers will live. JS . Yes JS is not TS , as far as I know TypeScript files won't compile into a usable website.

Create a web artist. I will attach the main code of my web worker fuzzySearch ( ./assets/workers/fuzzysearch-worker.js

):

'use strict';

var pattern, originalList;
self.onmessage = function(event) {
    // Receive a message and answer accordingly
    pattern = event.data.pattern;
    originalList = event.data.originalList;
    self.doFuzzySearch();
};

self.doFuzzySearch = function() {
    var filteredList;

    console.time('internalFastFilter');
    filteredList = self.fastFilter(originalList, (item) => self.hasApproxPattern(item.searchField, pattern));
    console.timeEnd('internalFastFilter');

    // Send the results back 
    postMessage({ filteredList: filteredList });    
};

// The code above is purposely incomplete

      

In your ts file, declare a work variable (usually above the constructor):

private readonly searchWorker: Worker = new Worker('./assets/workers/fuzzysearch-worker.js');

      



In the constructor:

constructor(/* Other injected dependencies here */
    public ngZone: NgZone) {       

        this.searchWorker.onmessage = (event) => {
          // Inside ngZone for proper ChangeDetection
          this.ngZone.run(()=> {                        
            this.dataList = event.data.filteredList;
            console.timeEnd('searchWorker');
          })
        };        

  }

      

Finally, in your "action function", let's say doSearch

:

doSearch(event) {
    // ... extra code to do some magic

    console.time('searchWorker');
    this.searchWorker.postMessage({ command: 'doFuzzySearch', originalList: this.realList, pattern: searchFilter });

    // ... extra code to do some other magic
}

      

this.searchWorker.postMessage

makes a call. All heavy loading operations are allowed inside the webmaster.

Hope this helps. Regards.

+1


source







All Articles