Tom Close
Tom Close

Reputation: 620

How can I access a bower package as an ES6 module?

I'm trying to migrate an ember app to use the ember app-kit. The code requires the accounting.js library. In the pre-app-kit version the file was loaded via a script tag in index.html

<script src="http://cdnjs.cloudflare.com/ajax/libs/accounting.js/0.3.2/accounting.min.js"></script>

and accessed in the views through the global namespace

App.MoneyField= Em.TextField.extend({
  init: function() {
    this._super();
    var value = accounting.formatMoney(this.get("money") / 100, '');
    this.set('value', value);
  };
  // other functions omitted
});

In the app-kit version, I've included accounting.js as a bower dependency. In bower.json:

{
  "name": "ember-app-kit",
  "dependencies": {
    "handlebars": "~1.1.2",
    "jquery": "~1.9.1",
    "qunit": "~1.12.0",
    "ember": "~1.4.0-beta.2",
    "ember-data": "~1.0.0-beta.6",
    "ember-resolver": "git://github.com/stefanpenner/ember-jj-abrams-resolver.git#master",
    "ic-ajax": "~0.3.0",
    "ember-testing-httpRespond": "~0.1.1",
    "accounting":"~0.3.2"
  },
  "resolutions": {
    "ember": "~1.4.0-beta.2"
  }
 }

When I try to build the app, it gives the error

W117: 'accounting' is not defined.

I understand why this is and know I need some sort of import accounting from ... statement.

How do I import a package installed via bower as an ES6 module?

Upvotes: 10

Views: 2918

Answers (1)

bguiz
bguiz

Reputation: 28547

I know that this was asked a few months ago, but since then, Ember App Kit has been succeeded by ember-cli, and this provides a very straight forward means to access either bower or npm dependencies.

With regards to being accessed as ES6 modules:

  • Non-AMD assets cannot be accessed as an ES6 module, you simply access them through the global variable that they export.
    • e.g. moment
  • AMD assets, on the other hand, can be accessed through the ES6 import syntax
    • e.g. import { raw as icAjaxRaw } from 'ic-ajax';

Worth also mentioning, that ember-cli supports an add-on system now, which can make importing these things as simple as adding them to the package.json of your project. Some of the more popular libraries already have ember-cli addons for them. This post describes how you can write your own.

Upvotes: 1

Related Questions