Using jQuery with Aurelia
Asked Answered
O

4

7

I have an Aurelia app and in app.js I want to use jQuery.

So my config.js looks like:

System.config({
...
  map: {
    ...
    "jquery": "npm:[email protected]",
    ...
   }
}

And in app.js I import the jQuery like this:

var $ = require('jquery');

But when I require it, I get the blank site. Same it was with import:

import $ from 'jquery';

What is wrong?

Thanks

EDIT: ok, solved. The problem is, the jQuery code must be called inside the attached() mehtod. So like this:

export class Class1 {
    attached() {
        //jQuery code here
    }
}
Obolus answered 13/1, 2016 at 15:54 Comment(0)
W
9

You need to install jquery from https://github.com/components/jquery

But if you use aurelia-skeleton, you can import it from bootstrap

import 'bootstrap';

and then use $ everywhere in app, or

import $ from 'bootstrap'

Same is for jqueryui. If needed get it from https://github.com/components/jqueryui

Wenoa answered 13/1, 2016 at 16:32 Comment(0)
C
6

Just to be different! We use jQuery and I tried adding it via config.js and using import etc - which worked ok. But we also use a couple of js libraries that we load using a script tag in the main html page and these require jquery. I tried loading them using import too but they weren't really designed for it and it just got too complicated so in the end we just made life very simple:

script tag for jquery in the main html page
script tag from 3rd party js libraries in the main html page

job done!

It also has a potential benefit of being able to load both jquery and the libraries from a CDN should you wish to.

Perhaps lose the benefits of loading modules via import but we use both jquery and the other libs throughout the app so we're not really losing out plus I don't have to remember to import them when I create a new module :-)

Cranston answered 14/1, 2016 at 9:41 Comment(0)
W
1

jquery is installed in \jspm_packages\github\components (at least in my case). If this is your case you should use:

System.config({
...
  map: {
    ...
    "jquery": "github:components/[email protected]",
    ...
   }
}

Link to Example in plunker.

Westphal answered 13/1, 2016 at 16:36 Comment(2)
Ok, but how to import it into the controller? Why is not var $ = require('jQuery'); working?Obolus
I'm not sure with var $ = require('jquery') (be careful: jquery, not jQuery) but here is a link to a working version with import $ from 'jquery';Westphal
P
0

npm install jquery --save

and add to dependencies section of vendor-bundle in aurelia.json:

{
     "name": "jquery",
     "path": "../node_modules/jquery/dist",
     "main": "jquery.min.js",
     "exports": "$",
     "map": "jquery.min.map"
}

Then you can use $ in your code for jQuery as usual.

Puttyroot answered 10/11, 2021 at 19:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.