Dan L
Dan L

Reputation: 4439

Using an external node-installed JS library in Atom editor

I'm trying to figure out how to use external javascript libraries in the Atom editor. I used npm to install the momentjs library, since Atom uses node. However, I'm puzzled as to what to do now? I can't find a way to use the library in Atom.

I thought that I could go to the Atom init.coffee file and do a require "moment" (also tried require "momentjs") but nothing seems to work.

The whole reason behind this is so I can use some javascript libraries for formatting dates in a snippet (I have another SO question about that which I'll close if this solves it).

But this question is a general question about installing and running javascript libraries in Atom. I've looked through the Atom docs and Googled, but I can't find a good answer. I figured something like this would be pretty easy?

Upvotes: 2

Views: 1285

Answers (2)

As Atom bundle its own node version (and thus is not using your global version(s)) it won't load globally installed modules through require. However, the require method supporting absolute paths, you can still load any module if you know it's absolute path, which shouldn't be a problem in your specific case.

In your init script you can write:

momentjs = require('/path/to/momentjs')

But beware of modules that ships with binaries. Atom is using node 0.11.13 so if the module you're trying to require have been installed for a different version you'll get a Error: Module did not self-register.. In that case I'm afraid the only solution would be to install the module as a dependency of an Atom package (as suggested by @nwinkler).

Upvotes: 1

nwinkler
nwinkler

Reputation: 54437

You should be able to do the following when developing your own package:

Install moment using npm install --save moment - this will install the moment.js library as a dependency and register it in the package.json file

In your library, import it in your lib file:

moment = require 'moment';
myDate = moment().format();

Then you can use the moment object to format your timestamps.

All of this will only work if you're doing your own package, of course. Not sure if this will work with simple snippets as well.

Upvotes: 0

Related Questions