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 buttons are at the top right, the menus are in theMenu button at the left end of the tabs, and shortcuts use Ctrl where a Mac uses ⌘. The rest works the same way.

Esc

Type to search every docs page.

JSpark is downloading

When you open JSpark-Setup.exe, Windows may stop it once, because the installer isn’t code-signed yet. If the file came from jspark.app:

A blue Windows box, “Windows protected your PC”: Microsoft Defender SmartScreen prevented an unrecognised app from starting. Under it, the link More info, and the button Don’t run.

1Click More info.

The same box after More info: Application JSpark-Setup-1.4.0.exe, Publisher Unknown publisher, and the buttons Run anyway and Don’t run.

2Then click Run anyway.

You see this only once: updates install inside the app. More in Install JSpark.