Wechat search [front-end full stack developer] pay attention to this hair loss, stall, selling goods, continuous learning of the programmer, the first time to read the latest article, will give priority to two days to publish new articles. Attention can be a gift package, you can save a lot of money!

One surprising difference between Deno and Node.js is the number of tools built into the runtime. In addition to the Read-Eval-print Loop (REPL) console, Node.js requires third-party modules to handle most of the indirect coding activities, such as testing and linting. Deno’s built-in tools provide almost everything you need right out of the box.

Before we begin, please note: **Deno is new! ** Use these tools with caution, some may be unstable and have few configuration options. Other tools can have undesirable side effects, such as recursively processing each file in each subdirectory. It is best to test tools from a dedicated project directory.

Install Deno

Install Deno on macOS or Linux using the following terminal command:

curl -fsSL https://deno.land/x/install/install.sh | sh
Copy the code

Or from Windows Powershell:

iwr https://deno.land/x/install/install.ps1 -useb | iex
Copy the code

More installation options are available in the Deno manual.

Type deno — version to check for a successful installation to display the version numbers for the V8 JavaScript engine, the TypeScript compiler, and deno itself.

Upgrade Deno

deno upgrade
Copy the code

Or upgrade to a specific version, such as V1.3.0:

Deno upgrade - version 1.30.0Copy the code

Most of the following tools are available in all versions, but later versions may have more features and bug fixes.

Deno help

To view a list of tools and options, type the following command:

deno help
Copy the code

Eval-Print Loop (REPL)

As with Node.js, you can access the REPL expression evaluation console by typing deno at the terminal. Each input expression returns a result or undefined:

$ denoUsing CTRL +d or close()> const w = 'World';
undefined
> w
World
> console.log(`Hello ${w}! `);
Hello World!
undefined
> close()

$
Copy the code

You can reenter previously entered expressions by using cursor keys to navigate expression history.

Depend on the check

You can see the dependency tree for all modules by typing deno info

, where

is the path/URL of an entry script.

Consider the following lib.js library code with the exported hello and sum functions:

// general library: lib.js

/** * returns "Hello <name>!" String *@module lib
 * @param {string} name
 * @returns {string} Hello <name>! * /
export function hello(name = 'Anonymous') {
  return `Hello ${ name.trim() }! `;
};

/** * returns the total number of arguments *@module lib
 * @param {... *} args
 * @returns {*} total* /
export function sum(. args) {
  return [...args].reduce((a, b) = > a + b);
}
Copy the code

These can be used from the main entry script index.js in the same directory:

// main entry script: index.js

// import lib.js modules
import { hello, sum } from './lib.js';

const
  spr = sum('Site'.'Point'.'.com'.' '.'reader'),
  add = sum(1.2.3);

// output
console.log( hello(spr) );
console.log( 'total:', add );
Copy the code

Deno run. /index.js results:

$ deno run ./index.js

Hello SitePoint.com reader!
total: 6
Copy the code

You can use deno Info./index.js to check the dependencies used by index.js:

$ deno info ./index.jslocal: /home/deno/testing/index.js type: JavaScript deps: file:///home/deno/testing/index.js └ ─ ─ file:///home/deno/testing/lib.jsCopy the code

Similarly, you can check the dependencies needed for any module URL, but be aware that the module will be downloaded and cached locally the first time it is used. Such as:

$ deno info https://deno.land/std/hash/mod.tsDownload the Download https://deno.land/[email protected]/hash/mod.ts Download at https://deno.land/std/hash/mod.ts https://deno.land/[email protected]/hash/_wasm/hash.ts Download Download at https://deno.land/[email protected]/hash/hasher.ts https://deno.land/[email protected]/hash/_wasm/wasm.js Download Download at https://deno.land/[email protected]/encoding/hex.ts https://deno.land/[email protected]/encoding/base64.ts deps: https://deno.land/[email protected]/hash/_wasm/hash.ts https://deno.land/std/hash/mod.ts └ ─ ┬ ├ ─ ┬ https://deno.land/[email protected]/encoding/base64.ts https://deno.land/[email protected]/hash/_wasm/wasm.js │ └ ─ ─ ├ ─ ─ https://deno.land/[email protected]/encoding/hex.ts └ ─ ─ at https://deno.land/[email protected]/encoding/base64.tsCopy the code

For more information, see the Deno Manual: Dependency Checker.

Linter (grammar check)

Deno provides a linter to validate JavaScript and TypeScript code. This is an unstable feature that requires the — Unstable flag but does not change the file when used.

Linter helps find less obvious syntax errors and ensures that the code meets the team’s standards. You may already use linter like ESLint in your editor or from the command line, but Deno offers another option in any environment where it is installed.

To recurse all.js and.ts files in the current and subdirectories of Lint, type deno lint — unstable:

$ deno lint --unstable

(no-extra-semi) Unnecessary semicolon.
};
 ^
    at /home/deno/testing/lib.js:13:1

Found 1 problem
Copy the code

Alternatively, you can specify one or more files to restrict linter. Such as:

$ deno lint --unstable ./index.js
$
Copy the code

For more information, see Deno Manual: Linter. It contains a set of rules that you can add to code comments to ignore or enforce specific syntax. It includes a list of rules that you can add to code comments to ignore or enforce specific syntax.

A test run

Deno has built-in test runners for unit testing JavaScript or TypeScript functions.

The test is defined in any file named

test with an extension of.js,.mjs,.ts,.jsx, or.tsx. It must make one or more calls to deno.test and pass a test name string and a test function. The function can be synchronous or asynchronous, and the results can be evaluated using various assertion utilities.

Create a new test subdirectory with a file named lib.test.js:

// test lib.js library

// assertions
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts';

// lib.js modules
import { hello, sum } from '.. /lib.js';

// hello function
Deno.test('lib/hello tests'.() = > {

  assertEquals( hello('Someone'), 'Hello Someone! ');
  assertEquals( hello(), 'Hello Anonymous! ' );

});

// sum integers
Deno.test('lib/sum integer tests'.() = > {

  assertEquals( sum(1.2.3), 6 );
  assertEquals( sum(1.2.3.4.5.6), 21 );

});

// sum strings
Deno.test('lib/sum string tests'.() = > {

  assertEquals( sum('a'.'b'.'c'), 'abc' );
  assertEquals( sum('A'.'b'.'C'), 'AbC' );

});

// sum mixed values
Deno.test('lib/sum mixed tests'.() = > {

  assertEquals( sum('a'.1.2), 'a12' );
  assertEquals( sum(1.2.'a'), '3a' );
  assertEquals( sum('an'.null[],'ed'), 'annulled' );

});
Copy the code

To run all tests in all directories, type deno test, or use deno test


to run tests stored in a specific directory. Such as:

$ deno test. /test

running 4 tests
test lib/hello tests ... ok (4ms)
test lib/sum integer tests ... ok (2ms)
test lib/sum string tests ... ok (2ms)
test lib/sum mixed tests ... ok (2ms)

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out (11ms)

$
Copy the code

You can also specify a -filter string or regular expression to limit tests by name. Such as:

$ deno test --filter "hello". /test

running 1 tests
test lib/hello tests ... ok (4ms)

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out (5ms)
Copy the code

By passing the -failfast option, longer running tests can be stopped on the first failure.

For more information, see Deno Manual: Testing. There are also some third-party test modules, including Merlin and Ruhm, but these modules still use deno.test under the surface.

V8 Debugger

Deno offers the same V8 engine and debugger as Node.js. You can use Chrome or VS Code to connect to the debugger and view changes to variables and objects through the Code.

To start the debugger, run the script with -inspect or –inspect-brk, stopping on the first line. If you need to connect to the debugger from another device on the network, add its IP address and port, or use –inspect=0.0.0.0:9229 to allow connections from anywhere. Such as:

$Deno run - inspect - BRK = 0.0.0.0:9229 / index. JsThe Debugger listening on the ws: / / 0.0.0.0:9229 / ws/ceb123... Debugger session started.Copy the code

Open it in a new Chrome TAB and thendenoThe script will display as newThe remote target:

Note: “DevTools for Node” will not connect to Deno’s debugger, even though they are similar.

Click on targetinspectLink to start DevTools. If you’ve ever used client-side debugging, you’re familiar with it. The Sources TAB is the most useful, allowing you to step through the code:

For more information, see Deno Manual: Debugger.

Code formatting

The built-in code formatter automatically formats JavaScript and TypeScript code in a similar way to Prettier. Deno’s formatter is also opinionated and it is currently impossible to configure options.

To use it, type deno FMT to recursively format each file in each subdirectory. Such as:

$ deno fmt

/home/deno/testing/index.js
/home/deno/testing/test/lib.test.js
/home/deno/testing/lib.js
Copy the code

Alternatively, you can format one or more individual files, such as deno FMT./index.js.

If you examine the lib.test.js file, you’ll see that the formatter removes some Spaces and converts the string to use double quotes (“) :

// hello function
Deno.test("lib/hello tests".() = > {
  assertEquals(hello("Someone"), "Hello Someone!");
  assertEquals(hello(), "Hello Anonymous!");
});
Copy the code

Individual code blocks can be ignored by adding // deno-FMT-ignore comments. Such as:

// deno-fmt-ignore
const bin = [
              1.0.0.0.1.0.0.0.1,];Copy the code

The entire file can be ignored by adding the // deno-FMt-ignore-file comment at the top of the code.

For more information, see Deno Manual: Code Formatter.

Warning! Automatic formatting can adversely affect JSDoc annotations.

Document generation

Deno can generate documentation from JSDoc comments in source code that explain the purpose, parameters, and return values of a function. Currently, Deno only generates documentation for modules that export functions. Such as:

$ deno doc ./lib.js

Defined in file:///home/deno/testing/lib.js:9:0

function hello(name)
  return "Hello <name>!" string
  @module lib
  @param {string} name
  @returns {string} Hello <name>!

Defined in file:///home/deno/testing/lib.js:21:0

function sum(. args)
  Returns total of all arguments
  @module lib
  @param {... *} args @returns {*} total $Copy the code

Add the — JSON flag to output the document in JSON format.

For more information, see Deno Manual: Documentation Generator.

The script package

Your main script and all its dependencies can be bundled into a file using the following methods:

deno bundle <main-script> <output-script>
Copy the code

Such as:

$ deno bundle ./index.js ./index.bundle.jsBundle file:///home/deno/testing/index.js Emit ". / index. Bundle. Js "(3.13 KB)Copy the code

You can then execute the generated script:

$ deno run ./index.bundle.js

Hello SitePoint.com reader!
total: 6
Copy the code

This can be useful when distributing scripts to end users or deploying the final code base to a live server.

Note: Top-level await calls may fail when bundled, so asynchronous wrapper functions must be added. This is a known issue that will be fixed in a future Deno release.

For more information, see Deno Manual: Bundling.

Script installer

Deno scripts can be installed globally so that they can be run from anywhere on the file system. It is similar to installing the global Node.js module, but simpler and easier to use.

You must use the deno install command:

  1. Any required runtime permission flags, for example--allow-read.--allow-write--allow-net.
  2. Optional name of the installed script, with--name <scriptname>.
  3. An optional installation root directory, used--root <path>. If not, Deno will install the script toDENO_INSTALL_ROOTEnvironment variable or$HOME/.deno/bin/Path set in.
  4. Module path or URL.

The sample script above can be installed by:

$ deno install --name myscript ./index.js✅ Successfully installed myscript/home/deno /. Deno/bin/myscriptCopy the code

A myscript file will be created in the.deno/bin/ directory with the following contents:

#!/bin/sh
# generated by deno install
deno "run" "file:///home/deno/testing/index.js" "$@"
Copy the code

Myscript can now run anywhere on the system. Such as:

cd ~
$ myscript

Hello SitePoint.com reader!
total: 6
Copy the code

This process makes it easy to tell the user how to install the application from a published URL. Such as:

deno install --name myapp https://myserver.com/myapp.js
myapp
Copy the code

Deno does not currently provide uninstall or remove commands. The only way to remove the script is to manually remove the generated files from the.deno/bin/ directory or wherever it is installed.

For more information, see Deno Manual: Script Installer.

Complete Deno kit?

Deno’s tools are new and some are rudimentary, but the documented “standard” approach is beneficial. Node.js offers numerous third-party options, but this can lead to choice paralysis or constantly switching solutions. Are you still using the same Node.js test suite?

However, be warned: these built-in tools are likely to grow rapidly as Deno usage increases.


www.sitepoint.com by Craig Buckler