Should I use `require` or `import`?

When I started developing an Atom package (and started with JavaScript), I read the documentation and found code like this:

import { CompositeDisposable } from 'atom'

I therefore assumed that this is the recommended way to make APIs available to one’s code. When I needed more, e.g. the npm package fs, I found code like

fs = require('fs')

but wanting a consistent style, I figured out that it can be translated to

import fs from 'fs'

Now I’m trying to show a dialog, and found electron’s dialog with the instruction to use

const { dialog } = require('electron').remote

which I haven’t been able to translate into an import statement.

What should I do? Simply mix require and import? Is there a disadvantage to that, except for stylistic objections? If I don’t mix, should I rather use require or import? Is there actually a difference, except for syntax?

import ... currently requires a transpiler so far as I know. You can tell Atom to do this with // @babel or something (I can’t recall exactly). Eventually support will trickle down once the Electron version is upgraded enough.

const fs = require("fs"); translates to import * as fs from "fs";

foo = require("bar") is probably easier to use though. There is no penalty for mixing the two styles, but I’d stick to one or the other.

'use babel';


Never mix these

Yeah, that’s an alternative that also works

It is my understanding that seasoned coders recommend others to stay away from global imports. To me that means the better format (my guess) is closer to.

const { CompositeDisposable } = require('atom');

This is off-topic to Atom, yet I would value your opinion if you choose to reply.

  • What type of “import” method is best to use?

  • Should we avoid using a transpiler such as Babel?

The import style is no more global than the require style. Both are scoped to the file. Both support pulling specific methods (import { CompositeDisposable } from 'atom';).

The problem is that the one bundled with Atom is old and can’t be updated because it might break existing packages that rely on it (at least that’s the case with the CS and TS transpilers; I don’t actually know about the JS transpiler specifically). So in my opinion, it is better to not rely on them.

The scope of the imported class was not what I was aiming for.
Best if the article talks for me (assuming same applies to JS)

Yeah, but that’s why you would use import * as fs from "fs"; instead

That was kind of my suggestion to avoid the * import.

I use my own generators when creating Atom packages, they all have transpilers built-in. The benefits are modern language features, tree shaking and shorter activation times (e.g. for packages that can’t use activationEvents or activationCommands). Also, ES imports are the language standard.

1 Like