fr31b3u73r fr31b3u73r - 1 year ago 271
Node.js Question

Use JS library xml2js with Angular 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) {

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

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


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
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?

Answer Source

Yes, there is a better way.

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

For live demo, you can visit my Github Repo