10

OS

Mac OSX El Capitan

Versions

angular-cli: 1.0.0-beta.8 , node: 6.2.0, os: darwin x64

Description

I tried to add lodash library in angular-cli project:

  • npm install --save lodash
  • typings install lodash --global --save

Successfully installed in node_modules.

system-config.ts:

/** Map relative paths to URLs. */
const map: any = {
  'lodash': 'vendor/lodash',
};

/** User packages configuration. */
const packages: any = {
  'lodash': {
    format: 'cjs',
    defaultExtension: 'js',
    main: 'core.js'
  }
};

angular-cli-build.js

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'lodash/**/*.+(js|js.map)'
    ]
  });
};

And then I tried to import in a service in different ways:

  1. import { chunk, intersection, zip } from 'lodash';

    Error: Cannot find module 'lodash'
    
  2. declare var _; const {chunk, intersection, zip} = _;

     Error: Cannot find name 'chunk'
            Cannot find name 'intersection'
            Cannot find name 'zip'
    

I don't found the way to use lodash...

I did something wrong? I miss something? Is there an issue?

Thank you very much,

Aral.


Similar questions (but don't answer my question):

Official docs:

Aral Roca
  • 5,442
  • 8
  • 47
  • 78
  • 1
    you can see this answer http://stackoverflow.com/questions/37712677/angular2-angular-cli-installing-lodash-cannot-find-module/37718379#37718379 – pd farhad Jun 30 '16 at 04:11

2 Answers2

8

Change system-config.ts to:

const map: any = {
  'lodash': 'vendor/lodash',
};

const packages: any = {
  'lodash': {
    format: 'cjs',
    defaultExtension: 'js',
    main: 'index.js'
  }
};

And then import it as:

import 'lodash';
declare var _;

Finally use it as:

_.chunk();
codef0rmer
  • 10,284
  • 9
  • 53
  • 76
  • 1
    `import 'lodash'; declare var _;` This worked for me - did not even set format in packages. The `import * as _ from 'lodash';` syntax worked perfectly on Plunker... any explanation? – ootwch Jul 06 '16 at 23:23
  • @ootwch Plunkr link? – codef0rmer Jul 07 '16 at 12:19
  • Here you go - this plunker is not designed to demonstrate this, this is just one of my experiments. https://plnkr.co/edit/kAcaV16mlXrso8jWpq8C?p=preview – ootwch Jul 08 '16 at 08:48
1

@codef0rmer answer is good, but if you want specific lodash dependencies and not the whole library, here is an answer with example on how to do that: https://stackoverflow.com/a/38317093/1426570

Community
  • 1
  • 1
Urigo
  • 3,175
  • 21
  • 27