有没有办法将 Node 项目转换为 Deno?

Is there any way to convert a Node project to Deno?

我想将 Node.js 项目转换为 Deno。有没有可用的指南?

我当前的项目有很多 NPM 文件,并且已经在 TypeScript 中了。

有什么建议吗?

Deno 和 Node.js API 不兼容,当然你可以重用所有 javascript/typescript 代码,但你需要重构或添加 polyfill。

为了简化迁移,Deno 提供了 Node Compatibility librarystd/node,这仍然需要大量工作。

幸运的是 require 是已经支持的 polyfills 之一

import { createRequire } from "https://deno.land/std/node/module.ts";

const require = createRequire(import.meta.url);
// Loads native module polyfill.
const path = require("path");
// Visits node_modules.
const leftPad = require("left-pad");

console.log(leftPad('5', 5, '0'))

如果你运行那个例子:

npm i left-pad
deno run --allow-read node.js
// 00005

如您所见,left-pad 已从 node_modules/ 正确加载。因此,对于不依赖 Node.js API 的 NPM 包,您可以使用 std/node.

轻松地要求它们

这是一个list of all supported modules


现在,对于严重依赖 Node.js API 的软件包,您能做的最好的事情就是使用 Deno API.

重写它们

随着项目的成熟,将有更简单的方法将 Node.js 项目转换为 Deno。

IMO 对于在 Node.js 上完美运行的大型项目来说,迁移它们是不值得的。 Deno 和 Node.js 可以一起生活,不是一个或另一个。如果您愿意,可以在 Deno 上构建新项目而不是迁移旧项目。

查看 Denoify,它是一个可以满足您需求的构建工具。您不必编写工具为您完成的端口,文档中都有详细说明。

披露:我是作者。

从 Deno v1.15 开始,Node.js compatibility mode which is unstable and comes with some caveats. There is also an issue in the repo 跟踪节点兼容模式的进度。

引用自docs

Node.js compability mode

Starting with v1.15 Deno provides Node compatiblity mode that makes it possible to run a subset of programs authored for Node.js directly in Deno. Compatiblity mode can be activated by passing --compat flag in CLI.

⚠️ Using compatiblity mode currently requires the --unstable flag. If you intend to use CJS modules, the --allow-read flag is needed as well.

⚠️ Package management is currently out of scope for Node.js compatiblity mode. For the time being we suggest to keep using your current solution (npm, yarn, pnpm).

请查看

的文档