Use of require(lib) versus in Electron apps

Some libraries only expose their variables through a CommonJS interface. Others, like jQuery, will also expose them as global variables.

The reason you can’t just do <script src="https://stackoverflow.com/questions/37736836/..."></script> for a library that only exposes through CommonJS is that it won’t bind to the global space.

Binding with CommonJS

module.exports = myLibrary;

Bindings to the global scope

window.myLibrary = myLibrary;

If a library only does the former then you will not be able to access the value without using require. If a library only does the latter, then you will not be able to access it with require in the sense of const myLibrary = require('my-library')

In general, it’s a better idea to use CommonJS over global variables. Adding variables to the global scope can lead to name collisions and directly loading in your dependencies makes it easier for the next person to tell where that dependency came from. Not to mention, CommonJS allows static analysis tools to work better so you’re more likely to get relevant code completions and type definitions.

Using the example of jQuery, it would be better to use it like this.

// main.js
const $ = require('./js/jquery-2.2.4.min.js');
// could also be done like this if you install it as a Node dependency
// const $ = require('jquery');

$(document).ready(...);

<!-- index.html -->
...
<script src="https://stackoverflow.com/questions/37736836/main.js"></script>

TL;DR

Use require('my-library') when possible, load them as globals when it is not.

Leave a Comment