我正在使用 Deno 編譯一些 TypeScript,然后將其作為網頁的一部分提供,以便它在瀏覽器端運行。我正在嘗試在客戶端使用畫布元素,為此我需要類似CanvasRenderingContext2Dor的型別CanvasGradient,它們在lib.dom.d.ts中定義,但它們不可用:Deno 編譯會出現類似TS2304 [ERROR]: Cannot find name 'CanvasRenderingContext2D'.. (另一方面,型別Path2D(在同一檔案中定義)不會導致問題。)
注意:我知道當代碼在瀏覽器中運行時這些型別將存在于運行時,但我希望 Deno 在編譯時知道它們。
我嘗試過以某種方式包含 .d.ts 檔案。我嘗試過的事情:
- 在編譯器選項中指定
"libs": ["deno.window", "esnext"]等(在 deno.json 中)。 - 像這樣匯入型別:
/// <reference types="https://raw.githubusercontent.com/microsoft/TypeScript/main/lib/lib.dom.d.ts" />
- 或這個:
// @deno-types="https://raw.githubusercontent.com/microsoft/TypeScript/main/lib/lib.dom.d.ts"
其中一些嘗試根本不起作用,有些甚至沒有明顯決議。看起來我不明白 Deno 如何加載型別定義,例如它Path2D從哪里加載型別宣告。如何解決這個問題?
uj5u.com熱心網友回復:
在對程式進行型別檢查時,您需要將 Deno 配置為僅使用 DOM 和 ES 型別。您可以使用 Deno 組態檔中支持的 TypeScript 編譯器選項來執行此操作:
./deno.json:
{
"compilerOptions": {
"lib": [
"esnext",
"dom",
"dom.iterable"
]
}
}
這指示編譯器程式不會在 Deno 中運行,而是在具有這些環境全域型別的類似瀏覽器的環境中運行。
這是一個示例源檔案:
./main.ts
import {assertExists} from 'https://deno.land/[email protected]/testing/asserts.ts';
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
assertExists(ctx);
當您從其他 TypeScript 模塊匯入到這樣的模塊中時
- 將由 Deno 編譯,并且
- 注定要在類似瀏覽器的環境中執行
那么你必須打包結果,因為瀏覽器不能將 TypeScript 源模塊作為匯入處理:
deno bundle --config deno.json main.ts main.js
生成的 JavaScript 如下所示:
// deno-fmt-ignore-file
// deno-lint-ignore-file
// This code was bundled using `deno bundle` and it's not recommended to edit it manually
const { Deno } = globalThis;
typeof Deno?.noColor === "boolean" ? Deno.noColor : true;
new RegExp([
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))",
].join("|"), "g");
var DiffType;
(function(DiffType1) {
DiffType1["removed"] = "removed";
DiffType1["common"] = "common";
DiffType1["added"] = "added";
})(DiffType || (DiffType = {}));
class AssertionError extends Error {
name = "AssertionError";
constructor(message){
super(message);
}
}
function assertExists(actual, msg) {
if (actual === undefined || actual === null) {
if (!msg) {
msg = `actual: "${actual}" expected to not be null or undefined`;
}
throw new AssertionError(msg);
}
}
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
assertExists(ctx);
在程式編譯中使用該模塊是安全的,https://deno.land/[email protected]/testing/asserts.ts因為它會在嘗試使用其任何 API 之前對 Deno 命名空間進行運行時特性檢測。任何不這樣做的模塊都會導致運行時錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/433093.html
