It is possible in Node.js v14, but you need to use the import operator, rather than the import declaration.

$ node

Welcome to Node.js v14.4.0.
Type ".help" for more information.
> let myModule;
undefined
> import("./my-module.js").then(module => { myModule = module });
Promise { <pending> }
> myModule.foo();
"bar"
Answer from diachedelic on Stack Overflow
🌐
GitHub
github.com › nodejs › node › issues › 48084
REPL: import statement inside the Node.js REPL · Issue #48084 · nodejs/node
May 20, 2023 - Uncaught: SyntaxError: Cannot use import statement inside the Node.js REPL, alternatively use dynamic import Instead of: import assert from 'node: assert' use: const assert = await import('node: assert')
Published   May 20, 2023
🌐
GitHub
github.com › nodejs › node › issues › 19570
dynamic import can't be used in the REPL · Issue #19570 · nodejs/node
October 27, 2017 - > import('fs').then(console.log, console.log) Promise { <pending>, domain: Domain { domain: null, _events: { removeListener: [Function: updateExceptionCapture], newListener: [Function: updateExceptionCapture], error: [Function: debugDomainError] }, _eventsCount: 3, _maxListeners: undefined, members: [] } } > { TypeError [ERR_INVALID_URL]: Invalid URL: repl at onParseError (internal/url.js:226:17) at parse (internal/url.js:235:3) at new URL (internal/url.js:318:5) at normalizeReferrerURL (internal/process/esm_loader.js:18:10) at setImportModuleDynamicallyCallback (internal/process/esm_loader.js:51:37) at process._tickCallback (internal/process/next_tick.js:114:7) input: 'repl' }
Published   Mar 24, 2018
🌐
Stack Exchange
ethereum.stackexchange.com › questions › 114221 › where-do-i-place-the-code-from-the-uniswap-tutorial
hardhat - Where do I place the code from the Uniswap tutorial? - Ethereum Stack Exchange
> import { ethers } from "ethers"; import { ethers } from "ethers"; ^^^^^^ Uncaught: SyntaxError: Cannot use import statement inside the Node.js REPL, alternatively use dynamic import
🌐
GitHub
github.com › TypeStrong › ts-node › issues › 2039
Can't start a REPL · Issue #2039 · TypeStrong/ts-node
July 21, 2023 - ~/W/r/rwdom/domlib master• ↑2 [1] yarn run ts-node --files --esm -T yarn run v1.22.19 $ /home/skrat/Workspace/xxx/yyy/node_modules/.bin/ts-node --files --esm -T > import { Face } from 'src/rw/dom/model/document'; /home/skrat/Workspace/xxx/yyy/domlib/<repl>.ts:2 export {}; ^^^^^^ Uncaught SyntaxError: Unexpected token 'export' > Face /home/skrat/Workspace/xxx/yyy/domlib/<repl>.ts:1 import { Face } from 'src/rw/dom/model/document'; ^^^^^^ Uncaught: SyntaxError: Cannot use import statement inside the Node.js REPL, alternatively use dynamic import
Published   Jul 21, 2023
Top answer
1 of 2
27

You cannot use static import statements (e.g. import someModule from "some-module"), at the moment. I'm not aware of any efforts/tickets/pull requests/intents to change that.

You can use import() syntax to load modules! This returns a promise. So for example you can create a variable someModule, start importing, & after done importing, set someModule to that module:

let someModule
import("some-module")
  .then( loaded=> someModule= loaded)

Or you can directly use the import in your promise handler:

import("some-module").then(someModule => someModule.default())

For more complex examples, you might want to use an async Immediately Invoked Function Expression, so you can use await syntax:

(async function(){
    // since we are in an async function we can use 'await' here:
    let someModule = await import("some-module")
    console.log(someModule.default())
})()

last, if you start Node.JS with the --experimental-repl-await flag, you can use async directly from the repl & drop the async immediately invoked function:

let someModule = await import("some-module")

// because you have already 'await'ed
// you may immediately use someModule,
// whereas previously was not "loaded"
console.log(someModule.default())
2 of 2
0

Given the static nature of import statements and that the engine needs to know all static imports (before processing any non-import related code). You can see how the import statement really isn't compatible with interactive REPL support.

For example, import statements are allowed in the middle or end of a file, but they're hoisted and processed before "non-static-import related code".

What should the REPL do if you type a static import statement at the end of your REPL session?

It can't easily go back and rerun all your prior commands in light of this potentially fundamental change!

I didn't think about that until reading this. Thanks Kevin Qian who also has ideas.

Find elsewhere
🌐
Archlinux
copyprogramming.com › t › import-statement-inside-the-nodejs-repl-alternatively-use-dynamic
Import Statement Inside The Nodejs Repl Alternatively Use Dynamic - CopyProgramming
function, rather than the import statement., Dynamic import is supported in the REPL since Node.js 13., results in the following error: Uncaught SyntaxError: Cannot use import statement, Why can't Deno use import statement s outside of a module?, To import modules in Deno REPL, you can use dynamic import()
🌐
Michael Currin
michaelcurrin.github.io › dev-cheatsheets › cheatsheets › javascript › general › modules › dynamic-modules.html
Dynamic modules | Dev Cheatsheets
You cannot use import from syntax in the REPL, even with experimental mode. import fs from 'fs'; ^^^^^^ Uncaught: SyntaxError: Cannot use import statement inside the Node.js REPL, alternatively use dynamic import
🌐
Dek Genius
dekgenius.com › script-code-example › 82949-cannot-use-import-statement-inside-the-node-js-repl-alternatively-use-dynamic-import.html
Example Javascript for Cannot use import statement inside the Node.js REPL, alternatively use dynamic import-82949
code example for javascript - Cannot use import statement inside the Node.js REPL, alternatively use dynamic import You can study and learn programming as you wish in the content of this website.
🌐
Folkstalk
folkstalk.com › home › 2022 › october
Cannot Use Import Statement Inside The Node.Js Repl, Alternatively Use Dynamic Import With Code Examples
October 4, 2022 - The "SyntaxError: Cannot use import statement outside a module" occurs when we use the ES6 Modules syntax in a script that was not loaded as a module. To solve the error, set the type attribute to module when loading a script, or in your package. ...
🌐
Stack Overflow
stackoverflow.com › questions › 73073219 › ts-node-cant-use-dynamic-imports-or-import-statements-while-in-repl-or-eval-in
node.js - ts-node can't use dynamic imports or import statements while in repl or eval in the cli - Stack Overflow
using import statements on REPL · import * as test from './src/test'; //works but then when I try to use 'test' it gives //SyntaxError: Cannot use import statement inside the Node.js REPL, alternatively use dynamic import · using on the cli · ts-node --esm -e "import * as z from './src/test'; console.log(z); export {}" //gives //Cannot use import statement outside a module ·
🌐
GitHub
github.com › nodejs › node › commit › 465c262ac6
repl: improve static import error message in repl · nodejs/node@465c262
August 6, 2020 - .replace(/^\s+at\s.*\n?/gm, ''); const importErrorStr = 'Cannot use import statement outside a ' + 'module'; if (StringPrototypeIncludes(e.message, importErrorStr)) { e.message = 'Cannot use import statement inside the Node.js ' + 'repl, alternatively use dynamic import'; e.stack = e.stack.replace(/SyntaxError:.*\n/, `SyntaxError: ${e.message}\n`); } } else if (self.replMode === module.exports.REPL_MODE_STRICT) { e.stack = e.stack.replace(/(\s+at\s+REPL\d+:)(\d+)/, (_, pre, line) => pre + (line - 1)); Expand Down ·
Author   nodejs
🌐
Replit
ask.replit.com › t › import-problems › 23051
Import problems - Node JS
Python #88: Authenticate FinesseProperly using authentication to detect individual users using Repl Auth.
🌐
GitHub
github.com › privatenumber › tsx › issues › 471
static import not support in repl · Issue #471 · privatenumber/tsx
I tried to test some pieces of code copied from other source in the repl. But it seems does not support static import. I also tested with ts-node, it works for this scenario. > tsx Welcome to Node.js v20.11.0. Type ".help" for more information. > import {parse} from 'path'; import { parse } from "path"; ^^^^^^ Uncaught: SyntaxError: Cannot use import statement inside the Node.js REPL, alternatively use dynamic import: const { parse } = await import("path"); > > ts-node > import {parse} from 'path' undefined > parse [Function: parse] > I tested with non-repl environment, it works.
🌐
Node.js
nodejs.org › api › repl.html
REPL | Node.js v25.2.1 Documentation
If the REPL is run as standalone program, it is also possible to change the REPL's inspection defaults from inside the REPL by using the inspect.replDefaults property which mirrors the defaultOptions from util.inspect(). > util.inspect.replDefaults.compact = false; false > [1] [ 1 ] > copy · To fully customize the output of a repl.REPLServer instance pass in a new function for the writer option on construction. The following example, for instance, simply converts any input text to upper case: import repl from 'node:repl'; const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });
🌐
Hacker News
news.ycombinator.com › item
Exploring competitive features in Node.js v18 and v19 | Hacker News
February 4, 2022 - For the frontend, Vite works well, and NextJS if you're using React in particular · Uncaught: SyntaxError: Cannot use import statement inside the Node.js REPL, alternatively use dynamic import
🌐
Stack Overflow
stackoverflow.com › questions › linked › 58384179
Recently active linked questions - Page 2 - Stack Overflow
I'm trying to add a module to my project , following the doc I add this line to my index.js on my node.js project import { bkLabs } from '@berkelium/nlp-core'; but I get the following error ... ... When I run the following code block, I get the error message "SyntaxError: Cannot use import statement outside a module."
🌐
Quora
quora.com › What-does-the-syntax-error-cannot-use-import-statement-outside-a-module-mean-in-Node-js
What does the syntax error:'' cannot use import statement outside a module'' mean in Node.js? - Quora
Answer (1 of 3): In Node.js you have the option of using either ES Modules or CommonJS modules, and the [code ]import[/code] syntax belongs to ES Modules, which your file is not recognised as.