How to import a module inside the Deno REPL?
Asked Answered
B

2

12

Attempting to import a module in the Deno REPL results in the following error:

Uncaught SyntaxError: Cannot use import statement outside a module
    at evaluate (rt/40_repl.js:60:36)
    at replLoop (rt/40_repl.js:160:15)

I use the Node REPL to quickly test out code, almost on a daily basis. The ability to import external code without writing a script or dealing with temporary files is a huge convenience.

Why can't Deno use import statements outside of a module? Is it even possible to use external code in the Deno REPL?

Boot answered 13/8, 2020 at 20:19 Comment(1)
See github.com/denoland/deno/issues/1285Inflationary
P
22

Starting with v1.4.3, you can use top-level await in the REPL to dynamically import modules:

> const path = await import("https://deno.land/[email protected]/path/mod.ts")
> path.basename("/my/path/name")
"name"
Phonology answered 8/10, 2020 at 17:41 Comment(0)
N
8

If you also try to use import a from "a" in Node REPL, it will also throw the same error. Only require can be directly used to import modules in Node REPL.

For Deno, there is no built-in CommonJS loader. Therefore it does not even provide require for you to load stuff synchronously.

The technical reason of why static import cannot be used in REPL is that REPL is actually a script evaluation tool: instead of compiling what you write into an ES Module, they are treated as plain scripts and directly fed into the engine, in the way similar to <script> in the browser without turning on the type="module". (ES modules with static imports have the semantics of asynchronously loading dependencies and determining the "shape" of a module without even actually running it.)

To import modules in Deno REPL, you can use dynamic import(). Personally I sometimes do the following (loading is usually fast enough such that you will pretty much have mod value set before you continue using the mod in REPL):

$ deno
> let mod; import("./mod.ts").then(m => mod = m)
Promise { <pending> }
Check file:///[blah]/mod.ts
> mod
Module { a: 1, Symbol(Symbol.toStringTag): "Module" }
Neutrality answered 22/8, 2020 at 21:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.