0

I was using csv-parse succesfully in a Vue project. The code looks like this:

import * as csvParse from 'csv-parse';
const parse = require('csv-parse')

const parseOptions: csvParse.Options = {
    //options here...
};

var parser: csvParse.Parser = csvParse(parseOptions, function(data, err) {
    console.log(data);
}) as csvParse.Parser;

const parseCallback:csvParse.Callback = (err: Error|undefined, records: any, info: csvParse.Info) => 
{
    //code to run after parse...
};
parse(csvText, parseOptions, parseCallback);

We switched to Angular 8 and the same code started raising this error:

index.js:43 Uncaught ReferenceError: global is not defined
    at Object../node_modules/buffer/index.js (index.js:43)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/safe-buffer/index.js (index.js:2)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/readable-stream/lib/_stream_readable.js (_stream_readable.js:55)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/readable-stream/readable-browser.js (readable-browser.js:1)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/stream-browserify/index.js (index.js:28)
    at __webpack_require__ (bootstrap:79)

I added

declare function require(path: string): any;

to handle require in typescript. I also tried removing the require. I get the same error.

How can I fix this? Thanks.

1 Answers1

0

After installing the csv-parse you can change the polyfills.ts and add this line of code:

(window as any)['global'] = window;

Then in your app.module.ts, try to import the CSV module:

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        ...
        CSVModule.forRoot(),
        ...
    ],
    exports: [
        ...
    ],
    providers: [
       ...    ],
    bootstrap: [AppComponent]
})

Here's a related SO post.

EDITED

Regarding the error you encoutered, try to add this inside the polyfills.ts:

// @ts-ignore
window.Buffer = window.Buffer || require('buffer').Buffer;

This should solve your problem.

Jessica Rodriguez
  • 2,899
  • 1
  • 12
  • 27