Search code examples
javascriptangularsystemjs

Import external library to Angular 2 (Systemjs)


I'm trying to use this library in my Angular 2 project. I've tried: npm install search-query-parse --save And then:

  1. Adding via <script> in index.ts - doesn't understand export in file (understandably)

  2. Adding through RequireJS by adding it to the config file and then using import { searchQuery} from 'search-query-parser'; - I can see the file is loaded through the network inspector, though I can't use it... I get Unhandled Promise rejection: (SystemJS) Can't resolve all parameters

What am I missing?

EDIT:

Here is my system-config.ts (the relavant parts...)

map: {
  'search-query-parser': 'npm:search-query-parser'    
},
packages: {
  'search-query-parser': { main: './index.js', defaultExtension: 'js'
}

Solution

  • It largely depends on the module itself in your case.

    There are several ways to fix this, but the easiest one in this circumstance is using:

    import * as searchQuery from 'search-query-parse'
    

    This will fix the issue because it will import everything in the searchQuery constant, so you will use:

    searchQuery.parse(params)
    

    because the library exposes a .parse method.

    Alternatively, you can also import the parse method only:

    import { parse } from 'search-query-parse'
    

    and use it as parse(params)

    That is because the brackets notation ({}) will look exactly for the method / property exported by the module that exposes the name provided in the brackets.

    If you still have no success with both methods, it's likely that the module is not being include at all by SystemJS (however, an error should be shown in that case). There are several fixes for such an issue (where one of them is to search for a node or SystemJS module that actually is compliant with typescript), but the easiest one is looking for the HTML file where the systemjs config is included, locating the wrapper (System.import(app)) and, before such call, defining by yourself the module:

    System.set("search-query-parse", System.newModule(require('search-query-parse'));
    

    In this way, you're telling SystemJS that, at runtime, it needs to make the Node Module "search-query-parse" available under "search-query-parse", so using in typescript he vanilla-style require:

    const sqp = require('search-query-parser');
    

    Please note that there also are other ways to fix such an issue (usually through the systemjs file), however these likely are the easiest and portable ones.