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

北战南征 提交于 2020-05-29 06:26:24

问题


I want to convert a Node.js project to Deno. Is there any guide available?

My current project has lots of NPM files and it's already in TypeScript.

Any tips?


回答1:


Deno and Node.js APIs are not compatible, of course you will be able to reuse all javascript/typescript code but you'll need to refactor or add polyfills.

To ease migration Deno provides a Node Compatibility library, std/node, which still needs a lot of work.

Fortunately require is one of the already supported 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'))

If you run that example:

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

As you can see left-pad was loaded correctly from node_modules/. So for NPM packages that do not rely on Node.js API, you can easily require them using std/node.

Here's a list of all supported builtins


Right now, for the packages that rely heavily on Node.js API, the best thing you can do is rewrite them using Deno API.

As the project matures there will be easier ways to convert a Node.js project to Deno.

IMO for big projects working perfectly on Node.js it's not worth it to migrate them. Deno & Node.js can live together it's not one or the other. Build new projects on Deno if you prefer instead of migrating old ones.




回答2:


Check out Denoify, it's a build tool that does what you want. You don't have to write the port the tool do it for you, it is all detailed in the docs.

Disclosure: I am the author.



来源:https://stackoverflow.com/questions/61770240/is-there-any-way-to-convert-a-node-project-to-deno

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!