14
votes

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.

2

2 Answers

3
votes

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.

1
votes

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