乐闻世界logo
搜索文章和话题

How to import a module inside the Deno REPL?

1个答案

1

The method of importing modules in Deno's REPL (Read-Eval-Print Loop) environment is similar to that in Deno scripts, but there are specific considerations to note. Below are the detailed steps and examples:

Step 1: Start Deno REPL

First, open your terminal and enter deno repl to launch the Deno REPL environment. For example:

bash
$ deno repl

Step 2: Use the import statement to import modules

In Deno REPL, you can directly use the import statement to import modules. There are two primary approaches: importing directly from a URL or from a local file.

Example 1: Importing from a URL

Suppose you want to import a module providing date functionality, such as the date-fns library, you can directly import it using its URL:

javascript
import { format } from "https://cdn.skypack.dev/date-fns@2.23.0"

Then, you can use the format function to format dates:

javascript
console.log(format(new Date(2022, 0, 1), 'yyyy-MM-dd')); // Output: 2022-01-01

Example 2: Importing from a local file

If you have a local module, such as a file named utils.js, you can import it as follows:

javascript
import { hello } from "./utils.js"

Assuming the content of utils.js is:

javascript
export function hello() { return "Hello, world!"; }

Then, in the REPL, you can use:

javascript
console.log(hello()); // Output: Hello, world!

Notes

  • Ensure the path or URL is correct; otherwise, the import will fail.
  • If the module uses TypeScript, Deno automatically handles compilation.
  • Importing modules directly in the REPL may introduce a slight delay due to the need to download and compile the module.

By following these steps, you can flexibly import any required modules in Deno's REPL environment, offering developers significant convenience and flexibility.

2024年7月20日 18:58 回复

你的答案