Import Javascript Files Into Meteor project


#1

I bought a wrapbootstrap theme recently and wanted to convert into meteor project. I have a jquery module js file called “jquery.countTo.js” that I want to import into my meteor project. I am not sure how to do it.

these are the ways I tried:

1 - put it inside “compatibility” folder
2 - use jquery’s getScript to load the js file

Meteor.startup(function(){ $.getScript('../js/jquery.countTo.js', function(){}); });

3 - created a new package and in the package.js file I simply modify the line “api.mainModule()” to api.mainModule(‘jquery.countTo.js’); However, when I run the project, it crashes when it reads this package, from the error, I am assuming its because my package doesn’t know the file jquery.countTo.js depend on jquery. What more should I add to package.js to tell it that it needs to load jquery first.

none of these worked. I think the code might have loaded, but its functionality is not working,
its supposed to change the frontend number from 1 to a destionation number you want to display, by using html attributes “data-from” and "data-to"
For example, this is in HTML code:

<h2 class="timer mb5" data-from="1" data-to="15381" data-refresh-interval="20">1</h2>

Can someone who have experience incorporating theme into meteor project, Please advise how to deal with js files

Thank you very much!


#2

The best option is to use ES2015 modules.

Meteor does not support modules natively yet, but there are packages that bring this support.

For example, universe:modules.

With modules you can import and export some variables/functions/classes/etc:

// module1.import.js
import alertSomething from ‘./module2’

Meteor.startup(() => {
alertSomething();
});

// module2.import.js
export default function alertSomething() {
alert(‘something’);
}

https://atmospherejs.com/universe/modules


#3

Meteor does support modules (from v1.3).


#4

Maybe try to import like this bootstrap.min.css file in this github link: https://github.com/themeteorchef/base/blob/5251e2b22b4bf7685ff73ba844296a566887c418/imports/startup/client/index.js


#5

This approach should work, as long as you’ve put it inside a /client/compatibility folder. Here’s a quick working example:

  1. meteor create count-to-test

  2. Copy jquery.countTo.js to /client/compatibility/jquery.countTo.js

  3. Change /client/main.html to:

<body>
  <span class="timer" data-from="25" data-to="75"></span>
</body>
  1. Change /client/main.js to:
import { Template } from 'meteor/templating';
import { $ } from 'meteor/jquery';

import './main.html';

Template.body.onRendered(function onRendered() {
  $('.timer').countTo();
});

Run the app and it will increment properly.