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

4
  • have you tried adding "node" to your tsconfig.json->compilerOptions->types array? Commented Mar 6, 2019 at 11:00
  • Are you able to reproduce this error on stackblitz? Commented Mar 6, 2019 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! Commented Mar 6, 2019 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 Commented Mar 6, 2019 at 11:29

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.