Original address: blog.logrocket.com/deno-1-0-wh…

By David Else

After nearly two years of waiting, Deno 1.0 will be officially announced on May 13th. Now that the API has frozen, the countdown has begun.

With the name of its founder and its forward-looking vision, Deno’s launch is undoubtedly one of the most exciting and controversial JavaScript issues in recent times.

Deno is a general-purpose JavaScript/TypeScript programming environment that integrates many of the best open source technologies to provide a comprehensive solution in a small executable file.

As the founder of Node.js, Ryan Dahl created Deno. Deno takes advantage of new JavaScript features that have been added since Node.js was released in 2009, while also addressing the design flaws Ryan mentioned in his “Top 10 Regrets of Node.js.” Some people call it a successor to Node.js, but the author doesn’t say so.

Unlike node.js, which uses C++, Deno is developed using Rust and built on top of the Tokio (tokio.rs/, Rust asynchronous runtime) platform. But like Node.js, Deno uses a V8 engine to run JavaScript. The fact that TypeScript is built in to Deno is an obvious feature. Although it needs to be compiled into JavaScript before running, this process is done internally, so it looks like Deno natively supports TypeScript.

1. Get started

You can download deno as instructed on the official website homepage (deno.land/). To upgrade to the new version, run Deno Upgrade. If you installed an earlier version of Deno that is too low, try running the terminal script installation again.

To learn about Deno subcommands, use one of the following commands.

  • deno [subcommand] -h: Display summary
  • deno [subcommand] --help: Displays detailed information

This article introduces the highlights of Deno 1.0, including examples of applying them using the latest syntax. We’ll use TypeScript whenever possible, and the JavaScript equivalent is fine.

You will love Deno after reading this article. This article will officially take you through the doors of Deno development.

2. The security

Deno is secure by default. By contrast, Node.js has access to file systems and networks by default.

To run a program that needs to start a child process without authorization, for example:

deno run file-needing-to-run-a-subprocess.ts

Copy the code

If you need permissions, you’ll see a warning message:

error: Uncaught PermissionDenied: access to run a subprocess, run again with the --allow-run flag

Copy the code

Deno explicitly allows access to different parts of the system using command-line options. The most commonly used include:

  • The environment
  • network
  • File system read/write
  • Run child process

To see full permissions to include the sample, run deno run -h.

The best practice is to whitelist read, write, and NET permissions. This allows you to specify more specifically what Deno is allowed to access. For example, to grant Deno read-only permission to the /etc directory, you could do this:

deno --allow-read=/etc

Copy the code

2.1 Shortcut of Permission

Licensing your application every time you run it quickly becomes a hassle. To do this, you can use the following methods.

1. Allow all permissions

You can use –allow-all or shortcut -a. This is not recommended, because it gives you no control over specific permissions.

2. Write a bash script

Write a bash script to run the application and grant the application the minimum permissions it needs.

#! /bin/bash // Allow sub-process and file system write permission deno run --allow-run --allow-write mod.tsCopy the code

The downside of this approach is that you might have to write a script for each run, test, and package.

3. Use the task Runner

You can use the GNU tool make to create a file that contains a set of Deno commands and related permissions. A denO-specific version of Drake (deno.land/x/ Drake /) can also be used.

4. Secure executable Deno program

Use deno Install to install a Deno program with the permissions it needs to execute (github.com/denoland/de…). . After installation, the PATH of this program is in $PATH.

3. The standard library

The Deno standard library (deno.land/ STD /) contains commonly used modules, which are maintained by the Deno project and guaranteed to be used in Deno. The standard library covers the most commonly used tools, and the API style and features mirror the standard library of the Go language.

JavaScript has been criticized for its lack of a standard library. Users have to reinvent the wheel for this, and developers often have to search the NPM repository for modules that solve common problems that are supposed to be provided by the platform.

To solve complex problems, such as the React of third-party packages another matter, but like to generate UUID (en.wikipedia.org/wiki/Univer…). Such simple tasks are best done using standard libraries. These smaller libraries can be used as components for larger libraries, making development faster and less scary. I don’t know how many times a popular library has suddenly been declared obsolete, leaving users to either maintain it or find a replacement library. Surveys show that 10-20% of commonly used open source software packages are no longer actively maintained.

3.1 Built-in modules and corresponding NPM packages

Deno module instructions NPM package
colors Set the color for terminal output Chalk, Kleur, colors
datetime Help with JavaScriptDateobject
encoding Added support for external data structures such as Base32, binary, CSV, TOML, and YAML
flags Help with command line arguments minimist
fs Helps implement file system operations
http Supports access to local files over HTTP http-server
log Used to create logs winston
testing For unit testing and benchmarking chai
uuid UUID generated uuid
ws Helps create WebSocket clients/servers Ws

4. The built-in TypeScript

TypeScript is a superset of JavaScript that adds explicit type declarations. Any valid JavaScript is also valid TypeScript, so converting your code to TypeScript costs nothing. Just change the extension to.ts and add the type.

With TypeScript in Deno, you don’t have to do anything. Without Deno, you must compile TypeScript to JavaScript before running it. Deno builds internally for you, making it easier to use TypeScript.

4.1 Use your own tsconfig.json

Those familiar with TypeScript probably know that you use the tsconfig.json file to specify compilation options. But this file is not required when using Deno. Because Deno has its own default configuration. If you’re using your own tsconfig.json and the options conflict with Deno, you’ll see a warning message.

This feature requires using the -c option and specifying your own tsconfig.json.

deno run -c tsconfig.json \[file-to-run.ts\]

Copy the code

For details on the default tsconfig.json, refer to the Deno manual (github.com/denoland/de…). .

If you’re like most developers, you’ll be happy to hear that Deno uses Strict mode by default. Unless someone deliberately overrides this setting, Deno does everything it can to report sloppy parts of the code to users.

5. Deno is very close to Web standards

Web standards take a long time to develop, and once published, no one can ignore them. Frameworks come and go, but Web standards remain the same. Time spent learning Web standards is never wasted, because no one dares topple the Web. The Web will continue to exist and evolve for the foreseeable future, even to the end of your career.

Fetch is a Web API for fetching resources. There is a JavaScript method called fetch() in the browser. If you want to use the standard API in Node.js, you need to rely on a third-party Node Fetch (github.com/node-fetch/…). . In Deno, the API is built in, just like the browser version, right out of the box.

Deno 1.0 provides the following Web-compatible apis.

  • addEventListener
  • atob
  • btoa
  • clearInterval
  • clearTimeout
  • dispatchEvent
  • fetch
  • queueMicrotask
  • removeEventListener
  • setInterval
  • setTimeout
  • AbortSignal
  • Blob
  • File
  • FormData
  • Headers
  • ReadableStream
  • Request
  • Response
  • URL
  • URLSearchParams
  • console
  • isConsoleInstance
  • location
  • onload
  • onunload
  • self
  • window
  • AbortController
  • CustomEvent
  • DOMException
  • ErrorEvent
  • Event
  • EventTarget
  • MessageEvent
  • TextDecoder
  • TextEncoder
  • Worker
  • ImportMeta
  • Location

The above apis are in the top-level scope of the program. This means that if you don’t use any of the methods in the Deno() namespace, your code should run in both Deno and the browser. While Deno’s apis aren’t 100% Web standards-compliant, this is still a big plus for front-end developers.

6. ECMAScript module

One major change from Node.js is that Deno uses the formal ECMAScript module standard instead of the old CommonJS. Node.js didn’t support ECMAScript modules in 13.2.0 until late 2019, and even then support was patchy and required to include the controversial.mjs extension.

Deno has waved goodbye to the past by embracing modern Web standards in its modular system. Modules can be referenced using urls or file paths that contain mandatory extensions. Such as:

import \* as log from "https://deno.land/std/log/mod.ts";
import { outputToConsole } from "./view.ts";

Copy the code

6.1 Problems with Name Extensions

Deno expects modules to include file extensions, but TypeScript doesn’t:

Using extensions is logical and the obvious way to do it. Unfortunately, reality is more complicated than ideal. For now, you can use the Visual Studio Code Deno extension (7. Package management addresses this problem in the Deno project.

The TypeScript founders seem to have their own thoughts on this issue. I don’t think there will be an easy solution to this problem until CommonJS is finally abandoned.

We need a little more patience with wise but aging programming gurus. Let’s hope they get rid of these outdated formats and punish those who cling to them to harm us.

Deno’s package management has been turned upside down. Instead of relying on centralized repositories, Deno’s package management features decentralization. Anyone can host a package just like any type of file on the Web. (marketplace.visualstudio.com/items?item >…). Solve this problem in the Deno project.

The TypeScript founders seem to have their own thoughts on this issue. I don’t think there will be an easy solution to this problem until CommonJS is finally abandoned.

We need a little more patience with wise but aging programming gurus. Let’s hope they get rid of these outdated formats and punish those who cling to them to harm us.

[A centralized warehouse like NPM has its pros and cons, and this is where Deno is controversial.] (marketplace.visualstudio.com/items?item >…). Solve this problem in the Deno project.

The TypeScript founders seem to have their own thoughts on this issue. I don’t think there will be an easy solution to this problem until CommonJS is finally abandoned.

We need a little more patience with wise but aging programming gurus. Let’s hope they get rid of these outdated formats and punish those who cling to them to harm us.

7. Package management

Deno’s package management approach has been turned upside down. Instead of relying on centralized warehouses, Deno’s package management features de-centralization. Anyone can host a package just like any type of file on the Web.

A centralized warehouse like NPM has its pros and cons, and this is where Deno is controversial.

7.1 Deno’s new package management mechanism

How easy it is to import a package can be intimidating.

[import { assertEquals } from "https://deno.land/std/testing/asserts.ts";] (https://marketplace.visualstudio.com/items?item>https://marketplace.visualstudio.com/items?itemName=axetroy.vscode-deno </a>) solve this problem in the Deno project. </p><p>TypeScript's founders seem to have their own ideas about this. I don't think there will be an easy solution to this problem until CommonJS is finally abandoned. </p><p> For wise but aging programming gods, we need a little more patience. Let's hope they get rid of these outdated formats and punish those who cling to them to harm us. </p><h2 id=)Copy the code

Now let’s analyze the change.

  • Instead of a centralized package manager, you import ECMAScript modules directly from the Web.
  • No more “magic” Node.js module parsing. Now, intuitive syntax makes it easier to locate sources.
  • There is no more node_modules directory. Conversely, dependencies that download will hide on your hard drive and you won’t see them. If you want to reload the cache and download again, just add –reload after the command.

If you want to download dependencies near the project code instead of using the global cache, you can use the $DENO_DIR environment variable.

7.2 Searching for compatible Third-party Libraries

There is currently a user area for denO-compatible third-party libraries (deno.land/x/), but the navigation design is rudimentary. For example, you can’t search by popularity or downloads. It is expected that this user area will either be expanded or that alternative sites will emerge to host community-contributed third-party modules.

Although backward compatibility with Node.js is not officially supported, there are still many libraries and applications available under Deno. Some work out of the box, others require some tweaking to work.

Library type compatibility
Run it in a browser

Use ESM syntax
It should work out of the box

Try Pika CDN (www.pika.dev/cdn)
Run it in a browser

Use CommonJS syntax
Use JSPM. IO (jspm.io/) encapsulated in ESM syntax
Does not run in a browser

Does not use the Node.js API
Use JSPm. IO to encapsulate ESM syntax
Using Node. Js API It may not work, but try this official Compatibility layer for Node.js

(deno.land/std/node/)

7.3 Installing third-party Modules

Deno is still very new and the surrounding ecology is still to be perfected. At the time of writing, I recommend Pika (www.pika.dev/cdn) as the first place to search for compatible modules, after the standard and user libraries.

Pika developers already provide TypeScript Types for Deno via ECMAScript called x-typescript -Types (dev.to/ Pika /introd…). . To find a package in Pika:

  • Search at www.pika.dev/search first

  • Find compatible modules; As of this writing, searching react returns:

    Package found! However, no web-optimized "module" entry point was found in its package.json manifest.
    
    Copy the code

However, Preact is compatible. Click on it, click import, and copy the resulting import statement into your code:

The import \ * as PKG from 'https://cdn.pika.dev/preact@ ^ 10.3.0';Copy the code

Beyond 7.4 package. Json

The JavaScript ecosystem relies heavily on package.json. The file has ballooned to multiple roles, such as:

  • Save the project metadata
  • Lists the dependencies of the project strip version
  • Distinguish dependencies into dependencies and devDependencies
  • Define the entry to the program
  • Store terminal scripts associated with the project
  • Defining Type is a recent addition to improve support for ECMAScript modules
{"name": "Project name", // metadata "version": "1.0.0", // metadata "description": "My application", // metadata "type": "/ / module function module", "main" : "SRC/mod. Ts", / / modules "scripts" : {" build ": "npm run \_copy-build-files && rollup -c", "build-watch": "NPM run \_copy-build-files && rollup-CW"}, // Script function "license": "gPL-3.0 ", // metadata "devDependencies": {" @ rollup/plugin - typescript ":" ^ 3.1.1 track ", "a rollup" : "^ 1.32.1", "typescript" : "^ 3.8.3"}, / / version and classification function "dependencies" : {"tplant": "^2.3.3"}Copy the code

All of these features have been added over time and are now the standard way the JavaScript ecosystem works. Many people forget that this is not an official standard and only come up with these features when they are necessary. Since JavaScript is so popular, this should be rethought.

Deno isn’t going to replace package.json, but there are some solutions.

7.5 Version Management using DEps. Ts and URL

Deno has a convention for managing package versions using a special file called deps.ts. In this file, dependencies are exported again. This way different modules in the application can reference the same source.

Instead of telling NPM which version of a module to download, deps.ts puts the version in the URL:

Export {assert} from "https://deno.land/[email protected]/testing/asserts.ts"; Export {green, bold} from "https://deno.land/[email protected]/ FMT /colors.ts";Copy the code

If you want to update a module, you can change the URL in deps.ts. For example, replace @v0.39.0 with @v0.41.0 so that the new version will be used everywhere else. If you imported https://deno.land/[email protected]/ FMT /colors.ts directly into each module, you would have to search the entire application and replace it one by one.

There is also a security risk in assuming that previously downloaded modules are not affected by later downloaded modules. This is why there is an option to create lock files (github.com/denoland/de…) The reason why. This ensures that the newly downloaded module is the same as the original downloaded module.

7.6 deno docUse JSDoc for metadata

JSDoc was released in 1999, 21 years ago. It is currently the most used and supported JavaScript and TypeScript document approach. While not an official Web standard, JSDoc is a perfect alternative to all the metadata in package.json.

/\*\*
 \* @file Manages the configuration settings for the widget
 \* @author Lucio Fulci
 \* @copyright 2020 Intervision
 \* @license gpl-3.0
 \* @version 1.0
 \*

Copy the code

Deno has built-in support for JSDoc and uses it to build document systems. Although metadata like the above is not currently used, deno Doc reads the description of the function and its parameters.

/\*\*
 \* Returns a value of (true?) if the rule is to be included
 \*
 \* @param key Current key name of rule being checked
 \* @param val Current value of rule being checked
 \*\*/

Copy the code

To query your program documentation, use deno doc

.

deno doc mod.ts

function rulesToRemove(key: string, val: any\[\]): boolean
  Returns a value of if the rule is to be included

Copy the code

If your program is hosted online, use this online document viewer: doc.deno.land/.

Deno’s built-in tools

This is the area that affects front-end developers the most. The current state of JavaScript tools is pretty messy. Add TypeScript’s tools and the complexity increases even further.

JavaScript itself does not need to be compiled, so it can be run directly in the browser. You can quickly tell if there is a problem with your code. The bar is very low, just a text editor and a browser.

Unfortunately, this simplicity and low barriers have been unwittingly undermined by something called extreme tool worship. As a result, JavaScript development has become a complex nightmare. I went through a full course on how to configure Webpack. Life is short, and this nonsense is over.

The tooling mess has left many eager to get back to actually writing code, rather than fiddling with configuration files or agonizing over competing standards. Rome at Facebook (github.com/facebookexp…) Is a project that has emerged to solve this problem. At the time of writing, the project is still in its infancy. While the project is beneficial, Deno should be a more fundamental solution.

Deno itself is a complete ecosystem with runtime and its own module/package management system. That means its own built-in tools will have a wider range of applications. Here’s a look at the tools built into Deno 1.0 and how you can use them to reduce dependence on third-party libraries and simplify development.

Of course, Deno isn’t going to replace the entire front-end build chain just yet, but that day shouldn’t be far off.

8.1 test

The test runner is built into Deno’s core in the form of a deno.test () function, while the assertion library (deno.land/ STD /testing…) Also included in the standard library. AssertEquals (), assertStrictEq(), and less common assertions like assertThrowsAsync().

At the time of this writing, there was no test coverage. In addition, you need to use third-party tools such as Denon (deno.land/x/ Denon /) to set the monitoring mode.

To see all of the test runner’s options, use deno test –help. It’s still limited, but it probably contains many of the features you’re familiar with in programs like Mocha. For example, –failfast stops at the first error, while –filter can be used to filter tests to run.

1. Use the test runner

The most basic syntax is deno test. This command runs all files in the working directory that end with _test or.test and have an extension of.js,.ts,.jsx, or.tsx (such as example_test.ts).

import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; Deno.test({ name: "testing example", fn(): void { assertEquals("world", "world"); assertEquals({ hello: "world" }, { hello: "world" }); }});Copy the code

If your code uses DOM, you will need to provide your own tsconfig.json file containing lib: [” DOM “, “esNext “]. Details are given below.

2. The format

Formatting based on dprint (github.com/dprint/dpri…) “, is a Prettier replacement library that copies all the accepted rules for Prettier 2.0.

To format file, you can use deno FMT < files > or Visual Studio Code extension (marketplace.visualstudio.com/items?item), later will be introduced.

3. Compile and package

Deno can create simple packages from the command line Deno bundle, but it also exposes the internal compiler apideno.land/STD /manual…. , so users can control their own output and sometimes customize it for use in the front end. The API is currently marked unstable, so you need to use the — Unstable tag.

Deno has some Web-compatible apis, but it’s not complete. If you want to compile front-end TypeScript that references the DOM, you need to tell Deno the relevant types at compile or package time. You can use the compiler API option lib.

Deno has some Web-compatible apis, but it’s not complete. If you want to compile front-end TypeScript that references the DOM, you need to tell Deno the relevant types at compile or package time. You can use the compiler API option lib.

index.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta /> <title>Document</title> </head> <body> <h1 id="greeter">Replace me</h1> </body> </html>Copy the code

test-dom.ts

let greeter: HTMLElement | null = document.getElementById("greeter")! ; // Please forgive the Non-Null Assertion Operator greeter.innerText = "Hello world!" ;Copy the code

compile.ts

const \[errors, emitted\] = await Deno.compile("test-dom.ts", undefined, {
  lib: \["dom", "esnext"\], // include "deno.ns" for deno namespace
  outDir: "dist",
});

if (errors) {
  console.log("There was an error:");
  console.error(errors);
} else {
  console.log(emitted); // normally we would write the file
}

Copy the code

Here is the result printed from the terminal.

slightlyCopy the code

In the above example, we compiled the test-dom.ts file that references the DOM. The Deno default lib value is overridden in the lib option of deno.pile (), so esNext is required as well. To use the Deno namespace, you can also add deno.ns.

This is still a bit experimental, but I would like to see the bundle command evolve to something like tree shaking, like rollup.js.

8.2 debugging

Debugging is built into Dene, but as of this writing, the Visual Studio Code extension does not support it. To debug, perform the following operations manually.

  • Deno run-a –inspect-brk filetodebug.ts (note: grant only minimum permissions for your module)

  • Open Chrome ://inspect in Chrome or Chromium and you’ll see a screen like the one below

  • Click “Inspect” to connect and start debugging the code.

8.3 File Monitoring

Deno is built based on Rust Notify (github.com/notify-rs/n…) The file monitoring function of deno.watchfs () is used. Deno likes to expose powerful apis in the background and let users implement their own code as they like. So there is no –watch tag, and instead you need to create your own implementation or use a third-party module.

The only difficulty in writing your own file monitor is eliminating jitter. The API might fire many events in a row, and we might not want to do something more than once. Github user Caesar2011 solves this problem with 23 lines of TypeScript code using date.now () (github.com/Caesar2011/…) .

There is also a more advanced Deno file monitoring tool called Denon (deno.land/x/ Denon /), which is equivalent to Nodemon. If you want to monitor workspace changes and rerun tests, simply execute the following command:

denon test

Copy the code

9. Visual Studio Code plug-ins

Released axetroy in Visual Studio Market Place plug-in ([] (marketplace.visualstudio.com/items?item >…). Is the best extension yet. After installation, create a.vscode /settings.json file in the project directory and enable the extension independently for each project.

.vscode/settings.json
{
"deno.enable": true,
}
Copy the code

All the coding AIDS, including intellisense, can then be used.

Nodule 10.

The rapid growth of the JavaScript ecosystem itself is both good and bad. On the positive side, there have never been so many high-quality tools. On the negative side, the endless proliferation of frameworks and libraries can easily lead developers to grumble and even doubt their lives.

Deno manages to avoid many of the pitfalls of JavaScript development, but here are just a few.

  • By using Web standards, Deno is making its API more future-oriented. It also gives developers confidence that they don’t have to waste time learning things that are quickly out of date.
  • Strengthens JavaScript with TypeScript while removing compilation burdens for tighter integration.
  • Built-in tools mean common features are available right out of the box and no longer waste time searching for them.
  • The decentralized package management frees users from NPM, and the ECMAScript module system is a nice contrast to the old CommonJS.

While not yet a complete replacement for Node.js, Deno has become an excellent programming environment for everyday use.

11. Related articles

  • Rome: Get started with Facebook’s latest JS tools