Home > Web Front-end > JS Tutorial > Deno Modules: Usage, Best Practices & Node Module Imports

Deno Modules: Usage, Best Practices & Node Module Imports

Joseph Gordon-Levitt
Release: 2025-02-12 08:33:10
Original
617 people have browsed it

Deno Modules: Usage, Best Practices & Node Module Imports

Dig into the Deno module – if you are from Node.js, this will be the biggest workflow change you encounter. Learn how they work and how to use them best, how to use Node.js modules and npm packages in Deno, and more.

Node.js is a JavaScript runtime based on Chrome V8 engine developed by Ryan Dahl and released in 2009.

Deno is also a JavaScript runtime based on Chrome V8 engine developed by Ryan Dahl and released in 2020. It is created based on a decade of experience. This doesn't necessarily mean it's a sequel to Node.js or a more advanced alternative, but it does deviate from Node.js' path.

See also:

  • Our Deno guide, including our Deno content index (scroll to the end)
  • Comparison of Node.js vs. Deno, and a guide to selecting tools that suit a specific situation

Main differences: Deno natively supports TypeScript, security, testing and browser APIs. Module processing has received less attention, but it may be the biggest change in the way JavaScript applications are created. Before discussing Deno, let me take you back to a simpler era...

Key Points

  • Deno is a JavaScript runtime based on Chrome V8 engine that deviates from Node.js by natively supporting TypeScript, security, testing and browser APIs. It also chooses to use ES2015 modules, which are imported from absolute or relative URLs, unlike Node.js using CommonJS.
  • Deno does not have a package manager like npm in Node.js. Instead, when it first encounters a module's URL in the script, it downloads and caches it to the global directory, meaning that no matter how many projects refer to it, only a copy of the specific module version is needed.
  • Deno allows versioning of module URLs so that specific code versions can be referenced. It also supports importing each module used in a project using a single dependency file, or assigning a name to a full or partial URL using an import map.
  • The platform has built-in security, restricts file system and network access, and provides integrity checking options. It also supports the use of the Node.js API and cross-platform modules that run on Node.js and Deno without special processing, and such modules may become increasingly popular as the JavaScript runtime ecosystem continues to evolve The more common it is.

Node.js module

In 2009, JavaScript did not have a standard module system. Part of this is because of its browser background, and it will take several years for ES6/ES2015 to appear.

Node.js is unimaginable if it does not provide modules, so it adopts CommonJS from several workarounds in the community. This has led to the development of the Node Package Manager (npm), which allows developers to easily search, use and publish their own JavaScript modules.

npm usage has increased exponentially. It has become the most popular package manager ever, and by mid-2020 it hosted nearly 1.5 million modules with more than 800 new additions per day (Source: modulecounts.com).

Deno module

Deno Select to use the ES2015 modules, which you can import from absolute or relative URLs:

<code>import { something } from 'https://somewhere.com/somehow.js';
</code>
Copy after login
Copy after login
Copy after login

The script at this URL must export the function or other values ​​accordingly, for example:

<code>export function something() {
  console.log('something was executed');
}
</code>
Copy after login
Copy after login
Copy after login

Deno uses the same module system as implemented in modern web browsers.

Node.js also supports ES2015 modules...but this is complicated and still experimental. CommonJS and ES2015 modules look similar, but work differently:

  • CommonJS loads dependencies from the file system as needed when executing code.
  • The ES module will pre-parse from the URL to resolve further imports before executing the code.

Node.js must continue to support CommonJS and handle mixed ES modules. Therefore, it assumes:

  1. Files ending with .cjs use CommonJS
  2. Files ending in .mjs use the ES module
  3. Files ending in .js are CommonJS, unless The most recent package.json sets "type": "module", or node is executed with the --input-type=module option.
It can be understood why Deno chose a single standard module system. However, npm is an important factor in Node's success, so it's surprising that Deno canceled it.

No package manager.

One criticism of npm is the huge scale of the node_modules directory for each project. As a module requires a specific version of other modules, it can reach hundreds of megabytes in size.

Deno Modules: Usage, Best Practices & Node Module Imports

Deno downloads and caches it to the global directory when the first time Deno encounters the URL of a module in the script. So no matter how many projects refer to it, only a copy of the specific module version is needed.

I know you are thinking: "Ah, but if..."

…But Deno has the option to solve the problem raised by the module URL.

Unreliable URL

The URL may fail temporarily, change, or disappear permanently. This is a problem for any package manager, and npm has also encountered problems in the past (it also allows installation from URLs).

For critical Node.js applications, it is recommended to add your node_modules directory to your project's Git/other repository.

Deno supports similar options. You can set the DENO_DIR environment variable to the directory path in the current project, for example:

<code>DENO_DIR=~/myproject/deno_modules`
</code>
Copy after login
Copy after login
Used in Windows cmd:

<code>> set DENO_DIR="C:\myproject\deno_modules"
</code>
Copy after login
Copy after login
or Windows Powershell:

<code>> $env:DENO_DIR="C:\myproject\deno_modules"
</code>
Copy after login
Copy after login
When your application runs, Deno caches the modules to that directory so that they can be added to the project's source control repository.

You might also consider bundling dependencies into a single JavaScript or TypeScript file. The Deno bundle command can do this in one step:

<code>deno bundle myscript.js myscript.bundle.js</code>
Copy after login
Copy after login
where myscript.js is an entry script that is usually executed using deno run. The generated standalone myscript.bundle.js file can be deployed to a real-time server.

Bundle with top await

Deno supports top-level await: no need to wrap await call in an anonymous async function. Unfortunately, the top-level await fails in the bundle, so the wrapper function must be added. This is a known issue and will be fixed in a future release.

Last: Beware of random Deno modules on unusual URLs! Deno, Github, or Bitbucket URLs with good documentation and community input are generally safer.

Module Version Control

Ideally, the module URL should be versioned so that you can reference a specific code version. For example, the Deno standard library allows you to load specific versions of HTTP server modules:

<code>import { something } from 'https://somewhere.com/somehow.js';
</code>
Copy after login
Copy after login
Copy after login

You can also refer to the master branch:

<code>export function something() {
  console.log('something was executed');
}
</code>
Copy after login
Copy after login
Copy after login

But this will download the latest version, and future versions may be incompatible with your application.

You can use similar version control conventions to publish Deno modules on your own servers, but as it becomes more popular, your website may receive a lot of traffic. A more reliable way is to use a repository of services like GitHub and assign a git tag to each version. Services such as denopkg.com and unpkg.com can be used to provide publicly versioned module URLs.

Multiple module mentions

You may need to reference the same module URL in many files in the application code base. When you want to update the module, you need to change the URL in multiple places. Search and replace can work, but it is clumsy, error-prone, and increases the likelihood of merge conflicts.

Alternatively, you can use a single dependency file that imports each module used in the project. It is usually named deps.js or deps.ts:

<code>DENO_DIR=~/myproject/deno_modules`
</code>
Copy after login
Copy after login

You can then reference the Deno module from deps.js in any other project file:

<code>> set DENO_DIR="C:\myproject\deno_modules"
</code>
Copy after login
Copy after login

When the module is updated, you only need to change the single URL reference in deps.js.

Another option is to import the map. This is a small JSON file, usually named import_map.json, which assigns the name to the full or partial URL:

<code>> $env:DENO_DIR="C:\myproject\deno_modules"
</code>
Copy after login
Copy after login

You can reference the import map name in any script:

<code>deno bundle myscript.js myscript.bundle.js</code>
Copy after login
Copy after login

Then, when executing the application with deno run, import the JSON file:

<code>import { serve } from 'https://deno.land/std@0.61.0/http/server.ts';
</code>
Copy after login

Import maps are currently an unstable function, so the --unstable flag is required. This feature may change in future Deno versions.

Investigation integrity

The code referenced from the URL may be changed or hacked without your knowledge. Well-known websites have been hacked because they link directly to third-party client code. Imagine how much damage it would cause if a script could access the server resources.

Deno has built-in security, so scripts must be executed with flags such as --allow-read and --allow-net to limit file system and network access. This will help prevent some problems, but this is not a substitute for verifying module integrity!

Deno provides an integrity check option. If you use a single dependency file (as mentioned above), it's easiest:

<code>import { serve } from 'https://deno.land/std/http/server.ts';
</code>
Copy after login

The following deno command generates a lock.json file containing the checksum of all imported Deno modules:

<code>import { something } from 'https://somewhere.com/somehow.js';
</code>
Copy after login
Copy after login
Copy after login

When another developer clones your project, they can reload each module and verify the integrity of each module to ensure they are the same as your module:

<code>export function something() {
  console.log('something was executed');
}
</code>
Copy after login
Copy after login
Copy after login

Deno does not enforce integrity checks. It is best to run these processes as automated Git hooks or similar operations.

Using Node.js module

Many Node.js APIs have been copied for Deno - see deno.land/std/node. This is not a complete list, but you will find common files, events, buffers, and utility modules.

The collection of nearly 800 third-party Deno modules is provided on

deno.land/x. There are frameworks similar to Express.js, database drivers, encryption functions, command line tools, etc.

You will also find a select list of popular modules, such as Awesome Deno.

However, you may be able to import any of the 1.5 million Node.js modules. Several CDNs can convert npm/CommonJS packages to ES2015 module URLs, including:

    Skypack.dev
  • jspm.org
  • unpkg.com
  • (Add ?module query string in URL)
Whether the module you need works properly in Deno is another matter.

Luckily, cross-platform modules that run on Node.js and Deno without special processing may emerge as the JavaScript runtime ecosystem continues to evolve.

More module questions

Referring to module URLs is controversial, and for those from very popular npm, it can be disturbing. That is, Deno simplifies the use of JavaScript modules. It addresses several npm criticisms while mitigating many potential side effects of the ES2015 module.

But this is far from perfect.

It is easy to publish npm modules, and it is also easy to search for npmjs.com. Your search terms may return 500 results, but by ranking packages by popularity, quality, and maintenance factors, you can minimize selection paralysis.

Submitting the code to a list of third-party modules in Deno is difficult. Modules must pass automated testing, but quality cannot be guaranteed, and the search results are arranged alphabetically. Once the number of modules reaches a few thousand, existing systems are unlikely to last.

It is also easy to update packages in npm. You can run npm outdated to view the update list, or just run npm install when referencing a looser version number in package.json.

There is no equivalent update check option in Deno. There are package manager-like projects available, including Trex, Update Deno Dependencies, and deno-check-updates, but these projects usually rely on import maps and always rely on semantic versioned URLs.

Should you switch to Deno?

Node.js did not die. It has matured and has ten years of experience in modules, technology, documentation and runtime.

Deno uses most of this knowledge, but it is very new and will develop rapidly in the coming years. It may be too early for large applications, but for small projects, the risk is less. Those who already use TypeScript or from other languages ​​may enjoy a much easier experience, but Node.js developers won't have any difficulty converting to Deno and then converting back.

However, Deno has an interesting advantage:

  • Its module system is the same as client JavaScript
  • It is implementing many browser APIs: you can reference window objects, set event listeners, start Web Workers, make remote server requests using the Fetch() API, and more.

The dream of isomorphic JavaScript libraries that work on either client or server is a big step forward.

Deno Basics

Learn about Deno quickly. Our collection of Deno basics helps you take the first step into the Deno world and beyond, and we keep adding content to it. We will provide you with the tutorials you need to become a professional. You can always update the index at the end of our Deno Getting Started Guide:

➤ Deno Basics

Frequently Asked Questions about Deno Module

What is a Deno module? The Deno module is a code unit in Deno, which is a secure runtime for JavaScript and TypeScript. Modules in Deno are similar to CommonJS modules in Node.js and ES6 modules in modern JavaScript. They enable developers to organize and share code by breaking it down into reusable and encapsulated blocks.

How to create modules in Deno? Creating modules in Deno is simple. You can create a new file (for example, module.ts), define your functions or classes, and then export them using the export keyword. Other Deno scripts can import and use these modules.

How to import modules in Deno? To import a module in Deno, you can use the import keyword followed by the path or URL of the module. Deno supports local and remote imports.

Can I use third-party modules in Deno? Yes, Deno supports importing modules directly from URLs, allowing you to use third-party modules hosted on package registry or GitHub repository.

The above is the detailed content of Deno Modules: Usage, Best Practices & Node Module Imports. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template