Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use aws-sdk inside webworker of Angular 9?

I installed aws-sdk :- npm install aws-sdk

And then imported aws-sdk inside my worker file like this:

app.worker.ts :- import * as AWS from 'aws-sdk';

And then tried to console.log inside addEventListener code is here:-

    addEventListener('message', async ({ data }) => {
    console.log(AWS);
}

After doing this i am getting errors as in screenshot:

enter image description here

I also tried to solve this error for that i defined global in polyfills.ts though it's not working

polyfills.ts :- (window as any).global = window;

Any help will be greatly appreciated. What i am trying to achieve is i am trying to upload file from worker using aws-sdk to s3 from my angular project. Thank you guys!

like image 403
narayan nyaupane Avatar asked Dec 30 '25 03:12

narayan nyaupane


1 Answers

It may help for others too so I am giving the solutions how I solved the issue:-

Web Workers don't have a global window object. So to access the global object we can use selfinstead.

So to solve my problem I followed these steps:

Steps :-

  • In the app.worker.ts, To use the Type-Script definition files with the global AWS object in a front-end project. We have to add reference types at the top of the worker file e.g /// <reference types="aws-sdk" />.

  • Define window const window = self;

  • And after the that import aws-sdk scripts importScripts('assets/js/aws-sdk.js'); then we'll be able to access the AWS object inside addEventListener('message', async ({ data }) => { console.log(window.AWS) });

  • Here i am importing scripts from assets because i had to customized aws-sdk to avoid window not defined error while calling s3.createMultipartUpload()

  • Here is the link https://raw.githubusercontent.com/nyaupane/customized_aws_sdk/master/assets/js/aws-sdk.js of customized aws_sdk in case if your requirement is same as mine otherwise you can customize according as your requirement.

  • Final app.worker.ts will look like this: https://github.com/nyaupane/customized_aws_sdk/blob/master/assets/worker/app.worker.ts

Now it works perfectly for multipart uploading...using aws_sdk in angular9 web worker.

like image 186
narayan nyaupane Avatar answered Jan 01 '26 20:01

narayan nyaupane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!