Angular 6 Uncaught ReferenceError: Buffer is not defined

Ok, after an hour I finally managed to have cognito working on my Angular app (just after upgrading to 6.0).

About the message global is not defined (or something close can't remember). Add the following into index.html:

<!doctype html>
<html lang="en">
<head>
  ...

  <script>
    var global = global || window;
  </script>
</head>

Then, you'll probably get an error saying that Buffer is not defined.

Install the buffer package using npm or yarn. And add the following into polyfills.ts ():

global.Buffer = global.Buffer || require('buffer').Buffer;

Stackoverflow answers/github issues that helped me in case it's not fixed for you after that:

Upgrading to angular-6.x gives "Uncaught ReferenceError: global is not defined"

https://github.com/aws/aws-amplify/issues/840#issuecomment-389459988

https://github.com/aws/aws-amplify/issues/678

https://github.com/aws/aws-amplify/issues/153

https://github.com/crypto-browserify/createHash/issues/20


I add the same issue trying to run the randomBytes method from crypto and added in my polyfill.ts file the global and Buffer references.

Unfortunately, I still had the following error message: _stream_writable.js:57 Uncaught TypeError: Cannot read property 'slice' of undefined

After looking up in the _stream_writable.js file I saw that the undefined pointer was on a process.version.slice instruction.

To sum it up, adding the following lines to my polyfill files completely resolved it:

(window as any).global = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
(window as any).process = {
  version: ''
};

I hope it will help someone out...


I solved this problem using these declarations in polyfill.ts file. It was mentioned in this issue and I added necessary declarations for other problems too.

import * as process from 'process';
(window as any).process = process;
(window as any)['global'] = window;
global.Buffer = global.Buffer || require('buffer').Buffer;

@maxime1992
For me, in the beginning, this has also solved a problem that I detected since the migration to angular 6, ie a well-stated module but not found when you want to go on one of these views.
The problem came from there and not from my module import or other.

But when I start the ng test command, now I have this error :

DeprecationWarning: Tapable.plugin is deprecated. Use new API on .hooks instead

Apparently, this is a webpack problem.
So, I prefer use this solution :
Adding this line to polyfills.ts should resolve node global error

(window as any).global = window;

Thanks again !!!

Tags:

Angular