MenuTroubleshooting / require or import gives an error

Docs / Troubleshooting

require or import gives an error

Each Node Snippet runs as a Module or a Script. When the code needs the other one, the console offers to switch.

On this page

What the error means

A Node Snippet has a Load Mode, and Node loads it in that mode:

  • Module (ESM) uses import, export and top-level await. It is always strict.
  • Script (CommonJS) uses require, like node file.js. It is strict only with "use strict".

Code written for the other mode fails with one of these errors. In a Script, the error starts with the number of the line that caused it.

The Snippet isThe code usesThe console says
a Modulerequire, module, exports, __filename or __dirnameNode’s error, such as ReferenceError: require is not defined in ES module scope, you can use import instead
a Scriptimport or exportLine 1: import and export need a Module. This Snippet is a Script — CommonJS, the way `node file.js` runs — so use `require(...)` instead, or switch it to Module.
a Scripttop-level awaitLine 3: Top-level await needs Module. Switch to Module, or wrap it in an async function.

Switch the Load Mode

Under each of these errors, the console shows a button for the other mode.

  1. Press Switch to Script (CommonJS) or Switch to Module (ESM).

The Snippet runs again at once, in the new mode. It keeps that mode from then on.

The Module Snippet uses require and throws; after the switch, it runs as CommonJS.

The button is the only way to change the Load Mode of a Snippet you already have. It is not offered in the Timeline. You can also change the code instead: use import in a Module, or require in a Script.

New Snippets

Settings → Running → New Snippets run as sets the mode for Snippets you make from now on. Snippets you already have keep theirs. See Load Mode.

The pictures show JSpark on a Mac. On Windows, the window looks a little different and uses Ctrl for ⌘, but everything works the same way.

Esc

Type to search every docs page.