Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buffer is not defined error after migrating to Angular 7

Tags:

angular

I am migrating an Angular 5 app to version 7 and have hit an issue with some existing code that attempts to use a Buffer global.

The code in question comes from the btoa library which makes use of the global.

In my migrated Angular 7 app, I am getting ReferenceError: Buffer is not defined and is being thrown when attempting to call the btoa function exported from this library.

This however works all fine in my Angular 5 app.

What could be going on here? I am assuming it has to do with a change in the angular CLI and maybe the way webpack is bundling somehow?

I saw a similar question here talking about related issues, and one suggestion was to install the buffer package, which I tried, but it made no difference for my situation.

Thanks

like image 443
mindparse Avatar asked Nov 28 '22 00:11

mindparse


1 Answers

Angular ver 7.2

  1. install buffer

$npm install buffer

  1. install node

$npm i @types/node

  1. then add 'node' to your tsconfig.app.json not tsconfig.json

     "compilerOptions": {
        "outDir": "../out-tsc/app",
        "module": "es2015",
        "types": ["node"]
      },
    

make sure

"typeRoots": [
  "node_modules/@types"
],

in your tsconfig.json

4.add global.Buffer to your polyfills.ts

(window as any).global = window;
(window as any).global.Buffer = (window as any).global.Buffer || require('buffer').Buffer;
like image 59
YoungHyeong Ryu Avatar answered Dec 22 '22 11:12

YoungHyeong Ryu