4

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

mindparse
  • 6,115
  • 27
  • 90
  • 191
  • have you tried adding `"node"` to your `tsconfig.json->compilerOptions->types` array? – Poul Kruijt Mar 06 '19 at 11:00
  • Are you able to reproduce this error on stackblitz? – Yaseen Ahmad Mar 06 '19 at 11:03
  • @PierreDuc - I tried that but it makes no difference. I didnt expect it to since I didnt have this in my tsconfig for my angular 5 version anyway. But thanks for the suggestion! – mindparse Mar 06 '19 at 11:15
  • the btoa library you are referencing is for node.js. It uses the `Buffer` global which is only available inside `node`. Not in the browser. For proper compilation, you need to have the node js typings, and `node` inside your types array. If you do not run your application inside nodejs, you don't need the btoa package – Poul Kruijt Mar 06 '19 at 11:29

1 Answers1

27

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;
Community
  • 1
  • 1
YoungHyeong Ryu
  • 929
  • 7
  • 9
  • It seems step 2 `$npm i @types/node` and 4 `(window as any).global = window; (window as any).global.Buffer = (window as any).global.Buffer || require('buffer').Buffer;` of your guide are not necessary for **Ionic 4** with **Angular 8**. – Patronaut Nov 14 '19 at 09:07