Cryptocurrency Research Lab.

Cryptocurrency関連技術についての調査・研究

Denoからnpm ライブラリの呼び出し方法

Deno から Node.js の npm ライブラリを使うことには課題があり、これまでesm.shなどを利用する必要があるなど苦労していましたが、Deno V1.25.0以降、import文のfrom句に「npm:<ライブラリ名>」と指定することで参照できるようになりました。

まだ Experimental レベルですから『--unstable』を指定する必要はありますが、公式にnpm ライブラリを簡単に取り込めるよう仕組みが用意されたことで、今後さならる利用が期待できそうです。

Express ライブラリ

$ deno run --unstable --allow-env --allow-read=. --allow-net=0.0.0.0:3000 main.ts
main.ts
import express from "npm:express";
const app = express();

app.get("/", function (req, res) {
  res.send("Hello World");
});

app.listen(3000);
console.log("listening on http://localhost:3000/");

Denoでは、Node.jsと違って node_modules ディレクトリは作成されず、共通のキャッシュディレクトリに保存されています。

$ deno info
DENO_DIR location: /home/halifax/.cache/deno
Remote modules cache: /home/halifax/.cache/deno/deps
Emitted modules cache: /home/halifax/.cache/deno/gen
Language server registries cache: /home/halifax/.cache/deno/registries
Origin storage: /home/halifax/.cache/deno/location_data

ethers ライブラリ

すべてのライブラリがすべて利用できるようになったわけではなく、8/26時点では、残念ながら ethers はまだ対応していないようです。

$ deno run --unstable --allow-env --allow-read createWallet.ts
error: Uncaught Error: Not implemented: crypto.Hmac
  throw new Error(message);
︙
createWallet.ts
import { ethers } from "npm:ethers";

const wallet = ethers.Wallet.createRandom();
console.log(`mnemonic: ${wallet.mnemonic.phrase}`);
console.log(`privateKey: ${wallet.privateKey}`);
console.log(`address: ${wallet.address}`);

従来通りに esm.sh 経由での利用できますから、対応を待つとしましょう。

import { ethers } from "https://esm.sh/ethers";