16

I am building an EmberJS application with the great help of ember-cli, which is great, but I have an error and I cannot find what I am doing wrong.

Here is what I do in my broccoli file:

app.import('vendor/underscore/underscore.js', {
    exports: {
        "underscore": [
            "underscore"
        ]
    }
});

and then in one of my controllers:

import _ from "underscore";

ember-cli builds my application.

But when I go to the controller using underscore, I get the error:

Error: Could not find module underscore.

What am I doing wrong?

djikay
  • 10,450
  • 8
  • 41
  • 52
Michael Chiche
  • 191
  • 1
  • 8

3 Answers3

5

Try:

app.import({
  development: 'vendor/underscore/underscore.js',
  production:  'vendor/underscore/underscore.min.js'
}, {
  'underscore': [
    'default'
  ]
});

This will at least give "import _ from 'underscore';" a chance to work. If you choose an AMD or ES6 version of underscore/lodash, list which modules you wish to import with 'default'.

EDIT:

Is it crucial that you use underscore? Why I ask, I'm using lodash with one Ember-cli project, and it is working fine.

Console> bower install lodash --save

then in Brocfile:

app.import({
  development: 'vendor/lodash/dist/lodash.js',
  production:  'vendor/lodash/dist/lodash.min.js'
}, {
  'lodash': [
    'default'
  ]
});


//or:
app.import('vendor/lodash/dist/lodash.min.js');

As for underscore - there was an issue with devDependencies not being bundled, of which underscore is one.

greg.arnott
  • 1,622
  • 17
  • 16
3

I got this from locks on #emberjs IRC.

https://github.com/ef4/ember-browserify

In your project:

npm install --save-dev ember-browserify
npm install --save-dev underscore

In your controller:

import _ from "npm:underscore";

Then you can use _. For example: _.each([1,2,3], alert);. I took everything out I had manually added to brocfile and package.json. Apparently this will do it for you. Crazy!

squarism
  • 3,242
  • 4
  • 26
  • 35
  • 1
    The issue here is that ember cli recommends using bower as your dependency manager. I think it's a good approach, but it fragments your dependencies and makes them more difficult to follow. At this point in time I've accepted using libraries such as lodash/underscore as globals by importing them in the `Brocfile` and declaring them with `/* global _ */` in order to appease jshint. – Mihai Scurtu Feb 24 '15 at 10:35
3

In recent versions of ember (I am using 2.11) it is possible to load AMD in UMD wrappers using

app.import('bower_components/js-md5/js/md5.js', {using: [{ 
   transformation: 'amd', as: 'js-md5' 
}]});

And in your code

import md5 from 'js-md5';

In your case of underscore it should look like:

app.import('vendor/underscore/underscore.js', {using: [{ 
   transformation: 'amd', as: 'underscore' 
}]});
Bruno Ranschaert
  • 7,428
  • 5
  • 36
  • 46