4

I need some help cause I don't have any idea what to do. I have to use 'amqplib' in my Angular project. Firstly I have tried to use 'amqp-ts', but as soon as I've opened a browser I had an error:Buffer is not defined

After several tries, I have switched to 'amqplib'. However when I'm trying call library's functions I get an error:Second error

The error occurs in line:

if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer
} else {
  // Copy properties from require('buffer')
  copyProps(buffer, exports)
  exports.Buffer = SafeBuffer
}

so again, Buffer is not defined.

I've tried several solutions mentioned here: Angular 6 Uncaught ReferenceError: Buffer is not defined and I have ended up with: -installed 'buffer' package

-in polyfills.ts

declare var require: any;
declare var global: any;

(window as any).global = window;
// @ts-ignore
window.Buffer = window.Buffer || require('buffer').Buffer;
(window as any).process = {
  version: ''
};

-in index.html

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

Nevertheless, none of them helped and still I have these errors :/

Jadw1
  • 139
  • 1
  • 2
  • 3

2 Answers2

6

I was trying to use crypto-browserify

I too ended up installing Buffer package using npm

then I was getting an error called :- Buffer is not a constructor here is what I did -

In polyfills.ts -

import * as Buffer from '../node_modules/buffer/index';
(window as any).global = window;
(window as any).process = {};
(window as any).process = window;
(window as any).process.browser = true;
(window as any).process.version = '';
(window as any).process.versions = { node: false };
(window as any).global.Buffer = Buffer.Buffer;
Abhi
  • 61
  • 1
1

I can't speak for previous versions of angular, but for angular 11. An elegant way to incorporate non-browser nodejs functions like buffer is to use webpack's polyfilling system

create a webpack.config.js file in the directory root and add these lines:

module.exports = {
  node: {
    Buffer: true
  }
};

then in you angular.json file, add the extraWebpackConfig option under build, test and serve json settings

"architect": {
        "build": {
          "builder": "ngx-build-plus:browser",
          "options": {
            "extraWebpackConfig": "webpack.config.js",

more details here: Buffer is not defined

nphias
  • 591
  • 4
  • 7
  • Not working for me, but I have a different builder `@angular-devkit/build-angular:browser`. This is in an ionic4-angular11 app, btw. – Mark Clark Apr 28 '21 at 21:41