Including an additional JavaScript File


I find the process of writing an Atom package anything but intuitive but I am trying my best …

I am writing a package using vanilla JavaScript. I’ve got something going, but I would now like to include a library of functions from a separate file, such as lib/library.js.

Here I grind to a halt. What is the process to have such as library and use it within the main code?


I wouldn’t know, because I’ve never made anything else before, but I found the process quite reasonable. Learning what all the components are (e.g., TextEditor vs TextBuffer, Grammars, Pane, etc.) took time, but I understood it after enough exposure.

I’m sorry, but that’s not quite true; you’re writing it using the Electron framework, which is built on and gives you access to the NodeJS framework / library / environment. You may not have used any features they have to offer yet, but you will if you want to import other files.

Because we are using NodeJS, we use require("path/to/file"). If you want to use a node module (like fs or lodash), you omit the path syntax and just provide the package name. You also need to add it to the dependencies in your package.json file (which is a NodeJS concept).


All Atom packages are Node modules, and you can extend Atom in the same way you extend an existing Node-based project. You require() each code file starting from your entry point. In each individual code file, you have to think about what you want to export. It’s usually easiest to just export an anonymous object rather than a bunch of functions. The following is almost a valid Node module (and would be if it had a package.json).

var exports = module.exports = {
  functionOne: () => { console.log("A function!") },
  functionTwo: () => { console.log("Another function!") }
export default exports

Of the above, keep in mind that the export default syntax is for exporting things to be require()ed directly of the file and module.exports is assigning the export to the object that Node has given us for registering exports. If you’ve written a stand-alone module that you’ve open-sourced on GitHub, but your main project uses so many of the internal functions of the module that you prefer to keep it integrated instead of splitting off entirely, then you might use both for different purposes. As I understand it, that’s fine too.