iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 21
2
Modern Web

強型闖入DenoLand系列 第 21

強型闖入DenoLand[20] - Testing and Related Tools(1)

Node.js之父新專案Deno 1.0正式亮相| iThome

強型闖入DenoLand[20] - Testing and Related Tools(1)

本篇章會分成三部分來介紹 Deno 原生的好用工具和功能:

  • Related Tools
    1. Script installer
    2. Formatter
    3. Bundler
    4. Documentation generator
    5. Dependency inspector
    6. Linter
  • Testing

列舉出來以後,就由筆者來一一做介紹吧!

腳本安裝

Deno 提供了腳本安裝器 deno install 讓使用者可以產生一個可執行腳本,簡單的範例如下:

deno install --allow-net --allow-read https://deno.land/std@0.73.0/http/file_server.ts

下完該命令後, Deno 會自動將該模組以及它的依賴模組快取到本地端:

Download https://deno.land/std@0.73.0/http/file_server.ts
Download https://deno.land/std@0.73.0/path/mod.ts
Download https://deno.land/std@0.73.0/http/server.ts
Download https://deno.land/std@0.73.0/flags/mod.ts
Download https://deno.land/std@0.73.0/_util/assert.ts
Download https://deno.land/std@0.73.0/path/_constants.ts
Download https://deno.land/std@0.73.0/path/win32.ts
Download https://deno.land/std@0.73.0/path/posix.ts
Download https://deno.land/std@0.73.0/path/common.ts
Download https://deno.land/std@0.73.0/path/separator.ts
Download https://deno.land/std@0.73.0/path/_interface.ts
Download https://deno.land/std@0.73.0/path/glob.ts
Download https://deno.land/std@0.73.0/encoding/utf8.ts
Download https://deno.land/std@0.73.0/io/bufio.ts
Download https://deno.land/std@0.73.0/async/mod.ts
Download https://deno.land/std@0.73.0/http/_io.ts
Download https://deno.land/std@0.73.0/path/_util.ts
Download https://deno.land/std@0.73.0/textproto/mod.ts
Download https://deno.land/std@0.73.0/http/http_status.ts
Download https://deno.land/std@0.73.0/bytes/mod.ts
Download https://deno.land/std@0.73.0/async/deferred.ts
Download https://deno.land/std@0.73.0/async/delay.ts
Download https://deno.land/std@0.73.0/async/mux_async_iterator.ts
Download https://deno.land/std@0.73.0/async/pool.ts
✅ Successfully installed file_server
C:\Users\UserName\.deno\bin\file_server.cmd

我們可以在命令列的最後看到,相關腳本已經被放到 C:\Users\UserName\.deno\bin\ 的路徑中:

% generated by deno install %
@deno.exe "run" "--allow-read" "--allow-net" "C:\Users\eric\.deno\bin\file_server.js" %*

自訂腳本檔名

我們可以使用 -n/--name 指定腳本名稱:

deno install --allow-net --allow-read -n serve https://deno.land/std@0.73.0/http/file_server.ts

如此一來,在 Windows 10 環境執行後,我們會得到 serve.cmd 的腳本檔案。

筆者會提到 Windows 10 只是因為我今天是用實驗室的電腦編寫文章跟測試功能,其他作業系統平台同樣適用上面提到的方法唷!

更改安裝目錄

根據上面的範例,其實不難發現, deno 腳本的預設安裝目錄為: .deno/bin/

若我們希望改變腳本的存放目錄,可以使用 --root : (該範例適用 Linux 環境)

deno install --allow-net --allow-read --root /usr/local https://deno.land/std@0.73.0/http/file_server.ts

安裝優先權:

  • --root 選項
  • DENO_INSTALL_ROOT 環境變數
  • $HOME/.deno

程式碼格式化

該功能是基於 dprint 實作出來的,至於什麼是格式化呢?

我們先來看亂七八糟的程式碼:

function sum(){
let a = 10;
	let b =20;
return a+ b;
}

上面是所謂的亂器八糟程式碼,假設筆者今天就是這種程式碼的製造者,想要洗心革面卻又不知道該從何下手,

在 Deno 中,就提供了這樣的工具可以幫你一鍵整理程式碼 (支援 TypeScript 以及 JavaScript ):

# format all JS/TS files in the current directory and subdirectories
deno fmt
# format specific files
deno fmt myfile1.ts myfile2.ts
# check if all the JS/TS files in the current directory and subdirectories are formatted
deno fmt --check
# format stdin and write to stdout
cat file.ts | deno fmt -

忽略格式化

如果使用者不希望有些程式碼被打理的漂漂亮亮(?),可以這麼做:

  1. 在程式碼前面加上 // deno-fmt-ignore :

    // deno-fmt-ignore
    export const identity = [
        1, 0, 0,
        0, 1, 0,
        0, 0, 1,
    ];
    
  2. 直接在程式碼頂部加上 // deno-fmt-ignore-file

程式碼打包工具

相似於 Webpack , Deno 提供了簡易的程式碼打包工具:

> deno bundle https://deno.land/std@0.73.0/examples/colors.ts colors.bundle.js
Bundle https://deno.land/std@0.73.0/examples/colors.ts
Download https://deno.land/std@0.73.0/examples/colors.ts
Download https://deno.land/std@0.73.0/fmt/colors.ts
Emit "colors.bundle.js" (9.83KB)

輸入 deno bundle [URL] colors.bundle.js 以後,我們就可以得到 colors.bundle.js

如果沒有聽過 Webpack 也沒關係,讀者可以參考今天的延伸閱讀。

出於好奇心,筆者也將之後會用到的範例程式拿出來打包看看:

原始檔 1 :

let a = function(i: number,j: number): number{
	return 3.5*i+(-6.6*j)
	}
function b(i: number,j: number) :number{
	return 6.6+(8.8*i)-3.5*j
	}
function MatrixC(i :number,j :number){
	let result = 0;
	for (var x = 1;x <= 60; x++) {
		let c = a(i,x)*b(x,j)
		result = result + c;
	}
	return result
}
export { a,b,MatrixC }

原始檔 2 :

import { MatrixC } from './index.ts';
let count = 0;
let start = new Date();
async function run(){
	for (var i = 1;i<=35; i++) {
		for (var j = 1; j<=35; j++) {
		let result = MatrixC(i,j);
		console.log(`C[${i},${j}]:${result}`)
	}
	}
	return new Date();
}

let end = await run()
console.log(end.getTime()-start.getTime())

打包後:

// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

// This is a specialised implementation of a System module loader.

"use strict";

// @ts-nocheck
/* eslint-disable */
let System, __instantiate;
(() => {
  const r = new Map();

  System = {
    register(id, d, f) {
      r.set(id, { d, f, exp: {} });
    },
  };
  async function dI(mid, src) {
    let id = mid.replace(/\.\w+$/i, "");
    if (id.includes("./")) {
      const [o, ...ia] = id.split("/").reverse(),
        [, ...sa] = src.split("/").reverse(),
        oa = [o];
      let s = 0,
        i;
      while ((i = ia.shift())) {
        if (i === "..") s++;
        else if (i === ".") break;
        else oa.push(i);
      }
      if (s < sa.length) oa.push(...sa.slice(s));
      id = oa.reverse().join("/");
    }
    return r.has(id) ? gExpA(id) : import(mid);
  }

  function gC(id, main) {
    return {
      id,
      import: (m) => dI(m, id),
      meta: { url: id, main },
    };
  }

  function gE(exp) {
    return (id, v) => {
      v = typeof id === "string" ? { [id]: v } : id;
      for (const [id, value] of Object.entries(v)) {
        Object.defineProperty(exp, id, {
          value,
          writable: true,
          enumerable: true,
        });
      }
    };
  }

  function rF(main) {
    for (const [id, m] of r.entries()) {
      const { f, exp } = m;
      const { execute: e, setters: s } = f(gE(exp), gC(id, id === main));
      delete m.f;
      m.e = e;
      m.s = s;
    }
  }

  async function gExpA(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](await gExpA(d[i]));
      const r = e();
      if (r) await r;
    }
    return m.exp;
  }

  function gExp(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](gExp(d[i]));
      e();
    }
    return m.exp;
  }
  __instantiate = (m, a) => {
    System = __instantiate = undefined;
    rF(m);
    return a ? gExpA(m) : gExp(m);
  };
})();

System.register("index", [], function (exports_1, context_1) {
    "use strict";
    var a;
    var __moduleName = context_1 && context_1.id;
    function b(i, j) {
        return 6.6 + (8.8 * i) - 3.5 * j;
    }
    exports_1("b", b);
    function MatrixC(i, j) {
        let result = 0;
        for (var x = 1; x <= 60; x++) {
            let c = a(i, x) * b(x, j);
            result = result + c;
        }
        return result;
    }
    exports_1("MatrixC", MatrixC);
    return {
        setters: [],
        execute: function () {
            a = function (i, j) {
                return 3.5 * i + (-6.6 * j);
            };
            exports_1("a", a);
        }
    };
});
System.register("for", ["index"], function (exports_2, context_2) {
    "use strict";
    var index_ts_1, count, start, end;
    var __moduleName = context_2 && context_2.id;
    async function run() {
        for (var i = 1; i <= 35; i++) {
            for (var j = 1; j <= 35; j++) {
                let result = index_ts_1.MatrixC(i, j);
                console.log(`C[${i},${j}]:${result}`);
            }
        }
        return new Date();
    }
    return {
        setters: [
            function (index_ts_1_1) {
                index_ts_1 = index_ts_1_1;
            }
        ],
        execute: async function () {
            count = 0;
            start = new Date();
            end = await run();
            console.log(end.getTime() - start.getTime());
        }
    };
});

await __instantiate("for", true);

執行結果: 正常!

需要注意的是,匯出程式碼的附檔名必須為 .js ,若是 .ts 會無法順利執行。

為什麼筆者知道呢?

因為: 我踩過的坑、我知道。

題外話

果然,就如同筆者的猜測,光是介紹三樣工具就佔了大部分的篇幅。

筆者之所以會拆成很多篇絕對不是因為:

  1. 沒有備稿
  2. 還沒去玩 Testing

我是非常負責任的,恩恩(?)

最主要的原因是:

我認為篇幅太長大家會懶得看,因為我自己每次看到落落長的文章就會不想看下去,我覺得一篇文章 3000 - 4000 字數是我自己可以接受的極限了 QQ

延伸閱讀

同樣的事情在不同人眼中可能會有不同的見解、看法。

在讀完本篇以後,筆者也強烈建議大家去看看以下文章,或許會對型別、變數宣告...等觀念有更深層的看法唷!


上一篇
強型闖入DenoLand[19] - TypeScript 和 Deno 的大小事(2)
下一篇
強型闖入DenoLand[21] - Testing and Related Tools(2)
系列文
強型闖入DenoLand37
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言