William
William

Reputation: 135

ember.js include custom js

Attempting to wrap my head around Ember.js. Seems I understand the complex things, but miss out on the little things.

How would one go about adding an example.js file? For simplicity, let's say the example.js file only contains:

(function(){
  console.log("example is alive in console");
})(window);

This should display "example is alive in console" within the browser console.

I have tried: adding app.import('vendor/javascripts/example.js'); within ember-cli-build.js and adding <script src="{{rootURL}}vendor/javascripts/example.js"></script> to index.html

Console is showing

ⓧ GET http://localhost:4200/vendor/javascripts/example.js
DEBUG: -------------------------------
DEBUG: Ember : 2.11.3
DEBUG: Ember Data : 2.12.1
DEBUG: jQuery : 3.2.1
DEBUG: -------------------------------
ⓧ GET http://localhost:4200/vendor/javascripts/example.js

All of the answers I have found stated that just adding custom.js to vendor file works. Sadly, I am missing something.

Upvotes: 1

Views: 2398

Answers (3)

William
William

Reputation: 135

When modifying ember-cli-build.js you MUST RESTART the ember server manually. The livereload server will not pick up the changes.

Upvotes: 2

Prabhakar Poudel
Prabhakar Poudel

Reputation: 339

Firstly, Ember.js has Convention Over Configuration approach, and your URL can do a lot of things than a normal HTML website.

Whatever you may want to do with your custom.js file it is not ember way of having it as a path. You need routes for navigation across the app. Although routes do much more than navigation. You specify the structure of your app that a user can browse through using Router's map function in app/router.js file.

However if you want to include custome.js file in your app, and have custom.js do some set of tasks for your app. You can simply go ahead and create a directory with any name, javascript for instance inside app directory. Have your javascript files placed inside it. Then you can import these files as simply as referencing any other files in ember:

import customObject from 'yourApp/javascript/custom.js';

Here, your custom.js should be exporting customObject.

Do read the guides if you want to learn more. And the API docs if you actually want to learn more.

Note: At the time of writing this answer current ember-cli version is @2.12.0

Upvotes: -1

S. Brage
S. Brage

Reputation: 36

This works for me when I don't nest assets in the /vendor directory. The ember-cli build process bundles JS files in /vendor into a single vendor.js file, which you can see linked in app/index.html. So place your example.js file at the root of /vendor, and then add the import to ember-cli-build.js:

app.import('vendor/example.js`);

Now when you start the server, your code from example.js should execute, since it will be included in assets/vendor.js.

Upvotes: 1

Related Questions