14

I was using ember-browserify to find npm modules in my ember-cli apps, but for some reason it does not work for ember-cli addons.

So my question is: Is there another way to import npm modules into an ember-cli addon?

Edit:

So I couldn't import the npm module, but I found that the specific module I wanted to import is also a bower component, so I installed it as so and imported it via the index.js like so:

included: function(app) {
  this._super.included(app);

  app.import('bower_components/dropzone/dist/dropzone.js');
}

and that worked. Doing this with the node_modules was not possible. It sucks that it is so hard to import npm modules to an ember-cli addon.

FutoRicky
  • 903
  • 2
  • 9
  • 22

2 Answers2

3

ember-fetch does this. The code is a bit complex:

treeForVendor: function(tree) {

  // Get the path of whatwg-fetch in node modules
  var fetchPath = require.resolve('whatwg-fetch');

  // use utility function to expand it into a pattern
  var expandedFetchPath = expand(fetchPath);

  // rename all the files in a tree containing files matching the pattern
  var fetch = rename(find(expandedFetchPath), function(path) {
    return 'whatwg-fetch/fetch.js'
  });

  // apply a template to each file in the tree and merge the trees
  return mergeTrees([
    new Template(fetch, templatePath, function variables(content) {
      return {
        moduleBody: content
      };
    })
  ]);
},

included: function(app) {
  this.app = app;
  this._super.included(app);

  // import the tree created above in treeForVendor
  app.import('vendor/whatwg-fetch/fetch.js', {
    exports: {
      default: [
        'default',
        'Headers',
        'Request',
        'Response'
      ]
    }
  });
}

Taken from https://github.com/stefanpenner/ember-fetch/blob/master/index.js

Hope this helps.

Gaurav
  • 12,662
  • 2
  • 36
  • 34
  • 1
    Im not following... Could you explain better? – FutoRicky Jul 31 '15 at 22:32
  • Like I said, the code is a bit complex. I'll add some comments for you to follow along, but it will take some work to adapt. – Gaurav Aug 01 '15 at 01:03
  • So I basically install ember-fetch and the node module is imported? Or do I have to install it and then add this code to my addon's index.js? – FutoRicky Aug 03 '15 at 15:17
1

In the addon, add the import to the app/ version of the object (this usually just exports the object).

In the app(s) that use the addon, install both ember-browserify and the npm module.

For example, in the app/models/user.js in an addon:

import TimezoneDetect from 'npm:jstimezonedetect';

export { default } from 'common/models/user';

See https://github.com/ef4/ember-browserify#using-ember-browserify-in-addons

kielni
  • 4,779
  • 24
  • 21