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.
What the error means
A Node Snippet has a Load Mode, and Node loads it in that mode:
- Module (ESM) uses
import,exportand top-levelawait. It is always strict. - Script (CommonJS) uses
require, likenode 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 is | The code uses | The console says |
|---|---|---|
| a Module | require, module, exports, __filename or __dirname | Node’s error, such as ReferenceError: require is not defined in ES module scope, you can use import instead |
| a Script | import or export | Line 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 Script | top-level await | Line 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.
- 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 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.