With the Meteor 1.3, the Meteor Development Group are releasing NPM support which can be a game changer for Meteor. We have been waiting this for a long and finally is here. Some people have tried to solve this problem before with sub-optimal solutions which felt really hacky. Now, NPM will be a first class citizen in Meteor and it will be fully supported.
Let’s explore what’s in.
Install Meteor if you don’t already have it:
curl https://install.meteor.com/ | sh
At the moment, Meteor 1.3 still in beta but you can give it a try:
meteor create meteor-npmcd meteor-npmmeteor update --release 1.3-modules-beta.4
Internally, it uses a modules package which doesn’t need to be added because it comes in the ecmascript package which is included by default because ECMAscript modules are part of the 2015 specification.
Next step is adding your package.json to your root directory as you would do in any other project that uses NPM. In this example I will be using a very simple package.json where I import mathjs, a well known mathematical library.
“description”: “Meteor + NPM Example”,
Now you can just run:
And you will see your node_modules folder with mathjs in it.
Using a NPM package
Now on the at the top of your meteor-npm.js file add the next line:
import math from ‘mathjs’;
As simple as it looks, now we can use mathjs in that file. For example, we can change the line 16 to:
Session.set(‘counter’, math.add(Session.get(‘counter’), 1));
Run your application with
And you are using a NPM library in your meteor application! I put everything together in a repo if you want to check it out:
This is a really simple example of how to use a NPM library in Meteor but it allow us to do amazing things. With this next patch we will be able to use any of the thousands of libraries that we have in NPM without any effort and not only utility libraries. We will be able to use our favorite frameworks like Flux, Redux, Vue.js, Backbone.js, etc. We will not be depending anymore on Atmosphere and we can be sure that we have the last up-to-date versions of our packages.
And not only that, we can use as well export to create our own objects and functions and make our application more modular, leaving behind the global namespacing pollution which was very common in Meteor.