Search code examples
javascriptnode.jstypescriptconvertersdeno

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


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?


Solution

  • As of Deno 1.25 there's an experimental NPM support by using npm: specifier

    How to use npm module in DENO?


    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 modules


    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.