Deno從web上全局支持location 。請(qǐng)繼續(xù)閱讀。
位置標(biāo)記
網(wǎng)頁(yè)的URL可以表示位置,但是deno進(jìn)程中沒(méi)有網(wǎng)頁(yè)。作為一個(gè)替代方案,我們?cè)试S用戶在cli命令后面加上--location參數(shù)來(lái)模擬文檔位置。它可以是http或httpsURL。
// deno run --location https://example.com/path main.ts
console.log(location.href);
// "https://example.com/path"
您必須通過(guò)--location <href>此程序才能工作。如果您不這樣做,則對(duì)location全局變量的任何訪問(wèn)都將引發(fā)錯(cuò)誤。
// deno run main.ts
console.log(location.href);
// error: Uncaught ReferenceError: Access to "location", run again with --location <href>.
設(shè)置location或其任何字段通常會(huì)導(dǎo)致在瀏覽器中導(dǎo)航。這在Deno中不適用,因此將在這種情況下拋出。
// deno run --location https://example.com/path main.ts
location.pathname = "./foo";
// error: Uncaught NotSupportedError: Cannot set "location.pathname".
擴(kuò)展使用
在網(wǎng)絡(luò)上,資源解析(不包括模塊)通常使用值 location.href作為任何相對(duì)URL所基于的根。這會(huì)影響Deno采用的某些Web API。
提取API
// deno run --location https://api.github.com/ --allow-net main.ts
const response = await fetch("./orgs/denoland");
// Fetches "https://api.github.com/orgs/denoland".
fetch()如果--location沒(méi)有傳遞該標(biāo)志,則上面的調(diào)用將拋出,因?yàn)闆](méi)有網(wǎng)絡(luò)類似的位置可以將其作為基礎(chǔ)。
worker模塊
// deno run --location https://example.com/index.html --allow-net main.ts
const worker = new Worker("./workers/hello.ts", { type: "module" });
// Fetches worker module at "https://example.com/workers/hello.ts".
僅在必要時(shí)使用
對(duì)于上述用例,最好是完整傳遞URL,而不要依賴--location。URL 如果需要,您可以使用構(gòu)造函數(shù)手動(dòng)建立相對(duì)URL 。
該--location標(biāo)志適用于那些出于某些特定目的要模擬文檔位置并且意識(shí)到僅在應(yīng)用程序級(jí)別有效的人員。但是,您也可以使用它來(lái)消除輕而易舉地訪問(wèn)location全局的依賴項(xiàng)中的錯(cuò)誤。