Skip to content

Instantly share code, notes, and snippets.

@tomysmile
Created December 9, 2016 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomysmile/0c51104b2e65bb2db2a361c3955bc9ae to your computer and use it in GitHub Desktop.
Save tomysmile/0c51104b2e65bb2db2a361c3955bc9ae to your computer and use it in GitHub Desktop.
ionic 2 - install lodash

Installation

To add an additional library to your app, you can run:

npm install <theLibraryName> --save

For example, to install Lodash:

npm install lodash --save

install will download a copy of the library from NPM, and save it in your app’s node_modules directory. --save will tell the NPM CLI to add an entry to your app’s package.json dependency list.

If this was just JavaScript, the process above would be enough for installing third party libraries. But Ionic uses TypeScript, there is an additional step to the process.

Since TypeScript utilizes static types, we need to be able to “describe” code we want to use and import. TypeScript does this through type definitions. The TypeScript team actually maintains a large collection of these, which can be installed through NPM as well.

Similar to our library installation, we can run:

npm install @types/theLibraryName --save

For our Lodash example, we can run:

npm install @types/lodash --save

In the rare case that types don’t exist for your library, there are two options to proceed. The simple option is to create a short-hand type definition. A more complicated and time consuming option is to create a create a complete type definition.

Here’s an example of calling the capitalize method in Lodash.

import lodash from 'lodash';
lodash.capitalize('myStringToCapitalize');

The best practice is to always try to import libraries using the named export approach, and only switching to the default export approach if there is an error when building.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment