I am having a hard time trying to get the lodash modules imported. I've setup my project using npm+gulp, and keep hitting the same wall. I've tried the regular lodash, but also lodash-es.
The lodash npm package: (has an index.js file in the package root folder)
import * as _ from 'lodash';
Results in:
error TS2307: Cannot find module 'lodash'.
The lodash-es npm package: (has a defaut export in lodash.js i the package root folder)
import * as _ from 'lodash-es/lodash';
Results in:
error TS2307: Cannot find module 'lodash-es'.
Both the gulp task and webstorm report the same issue.
Funny fact, this returns no error:
import 'lodash-es/lodash';
... but of course there is no "_" ...
My tsconfig.json file:
{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}
My gulpfile.js:
var gulp = require('gulp'),
ts = require('gulp-typescript'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
tsPath = 'app/**/*.ts';
gulp.task('ts', function () {
var tscConfig = require('./tsconfig.json');
gulp.src([tsPath])
.pipe(sourcemaps.init())
.pipe(ts(tscConfig.compilerOptions))
.pipe(sourcemaps.write('./../js'));
});
gulp.task('watch', function() {
gulp.watch([tsPath], ['ts']);
});
gulp.task('default', ['ts', 'watch']);
If i understand correctly, moduleResolution:'node' in my tsconfig should point the import statements to the node_modules folder, where lodash and lodash-es are installed. I've also tried lots of different ways to import: absolute paths, relative paths, but nothing seems to work. Any ideas?
If necessary i can provide a small zip file to illustrate the problem.
Here is how to do this as of Typescript 2.0: (tsd and typings are being deprecated in favor of the following):
$ npm install --save lodash
# This is the new bit here:
$ npm install --save-dev @types/lodash
Then, in your .ts file:
Either:
import * as _ from "lodash";
Or (as suggested by @Naitik):
import _ from "lodash";
I'm not positive what the difference is. We use and prefer the first syntax. However, some report that the first syntax doesn't work for them, and someone else has commented that the latter syntax is incompatible with lazy loaded webpack modules. YMMV.
Edit on Feb 27th, 2017:
According to @Koert below, import * as _ from "lodash";
is the only working syntax as of Typescript 2.2.1, lodash 4.17.4, and @types/lodash 4.14.53. He says that the other suggested import syntax gives the error "has no default export".