4

I installed the library lodash from npm and now i want to import it to my file like this:

import _ from 'lodash';

But i get this error:

Error TS1192: Module '"lodash"' has no default export.

Why I get this error? and how I can import node_modules that are not .ts files with the new import syntax of ECMAscript6?

user233232
  • 6,067
  • 9
  • 29
  • 37
  • See http://stackoverflow.com/questions/29596714/new-es6-syntax-for-importing-commonjs-amd-modules-i-e-import-foo-require/29598404#29598404 – C Snover Oct 25 '15 at 08:39

1 Answers1

5

The following two approaches works for me:

Using require:

/**
 * Install package via
 *   $ bower install lodash --save
 * Run:
 *   $ node test.js  # after TypeScript compilation
 */

// test.ts file
/// <reference path="typings/lodash/lodash.d.ts" />
import _ = require('./bower_components/lodash/lodash.js');
console.log(_.chunk(['a', 'b', 'c', 'd'], 2));

ES6 import:

/**
 * Install package via
 *   $ tsd install lodash --save # to download definition file
 *   $ npm install lodash --save
 * 
 * Run:
 *   $ node test.js  # after TypeScript compilation 
 */
// test.ts file
/// <reference path="typings/lodash/lodash.d.ts" />
import * as _ from 'lodash';

console.log(_.chunk(['a', 'b', 'c', 'd'], 2));
// → [['a', 'b'], ['c', 'd']]

Note: Path mappings based module resolution planned for TypeScript 1.8 (https://github.com/Microsoft/TypeScript/issues/5039)

nstCactus
  • 5,141
  • 2
  • 30
  • 41
MartyIX
  • 27,828
  • 29
  • 136
  • 207
  • 1
    But how typescript knows from where to pull the lodash library based on the definition file? – user233232 Oct 25 '15 at 08:51
  • Check this line: https://github.com/borisyankov/DefinitelyTyped/blob/master/lodash/lodash.d.ts#L9983 and you can see that the name 'lodash' is defined there, so no error is thrown on line `import * as _ from 'lodash';`. TypeScript compiler does not pull anything (check the compiled `test.js` file). – MartyIX Oct 25 '15 at 08:56