2

I´m trying to use xml2js as XML parser within an Angular 2 (RC 1 with TypeScript) webapplication. However I only get some errors and no working solution.

Here is what I did step by step:

  • installed xml2js via npm install xml2js
  • installed according d.ts-file via tsd install xml2js
  • included script link to my index.html: <script src="../node_modules/xml2js/lib/xml2js.js"></script>
  • configured SystemJS by adding 'xml2js': '../node_modules/xml2js' to map and 'xml2js': { defaultExtension: 'js' } to packages
  • import Parser of xml2js in my component via import {Parser} from 'xml2js';
  • try using it in constructor of component:
    var parser = new Parser(); var xml = "<root>Hello xml2js!</root>" parser.parseString(xml, function (err, result) { console.dir(result); });

This is what browser console tells me when opening a webpage containing the component:

module.js:440 Uncaught Error: Cannot find module 'sax'

and

GET file:///C:/xxx/source/node_modules/xml2js net::ERR_FILE_NOT_FOUND

as well as

index.html:17 Error: Error: XHR error loading file:///C:/xxx/source/node_modules/xml2js
at ZoneDelegate.invokeTask (file:///C:/xxx/source/node_modules/zone.js/dist/zone.js:356:38)
at Zone.runTask (file:///C:/xxx/source/node_modules/zone.js/dist/zone.js:256:48)
at XMLHttpRequest.ZoneTask.invoke (file:///C:/xxx/source/node_modules/zone.js/dist/zone.js:423:34)
Error loading file:///C:/xxx/source/node_modules/xml2js as "xml2js" from file:///C:/xxx/source/frontend/angular/components/mycomponent/mycomponent.js

"sax" is located in node_modules/xml2js/node_modules/sax as installed via npm. What did I miss installing the external library? Is there a "better" way to use external JS libraries with Angular 2 & TypeScript?

1
  • Same. Eventually it complained it can't find "events" or "timers" and had no idea how to deal with that. Commented Jun 18, 2017 at 23:59

1 Answer 1

2

Yes, there is a better way.

You can use System.set('xml2js', System.newModule(require('xml2js'))) to load your local xml2js module in systemjs.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! This is a great working, simple solution.
Unfortunately, when I try this, I see in the console a ReferenceError: Can't find variable require.
@sss4r Sorry, I don't know why it occurs. Too less information.
@sss4r I googled it and found it looks like a common issue, lots of github issues were talking about this question. Maybe you can find your answer there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.