如何在一处管理 Deno 依赖项

How to manage Deno dependencies in one place

在 Deno 中,可以在导入语句中对依赖项进行版本控制,并且没有像 npm 那样的 package.json

但是如何在一个地方管理它的 URL 和版本?

我将在整个系统中声明多个文件和依赖项。

例如:

dateUtils.ts

import { parseDate } from 'https://deno.land/std@0.50.0/datetime/mod.ts';

const DEFAULT_MASK = "dd-mm-yyyy";

export function parse(date: string): Date {
    return parseDate(date, DEFAULT_MASK);
};

service.ts

import { v4 } from "https://deno.land/std/uuid/mod.ts";

export function process(request: any) {
    const { token } = request;
    const isValid = v4.validate(token);

    console.log(`Token validity: ${isValid}`)

};

app.ts

import { parse } from "./dateUtil.ts";
import * as service from "./service.ts";

const date = parse("20-05-2020");
console.log(date);

const request = {
    token: "408d30e5-1e90-45e3-b299-6520feee6d76"
}
service.process(request)

deno 中有一个将导入合并到 deps.ts 的约定。

export { parseDate } from 'https://deno.land/std@0.50.0/datetime/mod.ts';
export { v4 } from "https://deno.land/std/uuid/mod.ts";

然后可以在您的应用程序的其他 modules/scripts 中导入导出:

import { v4 } from "./deps.ts";
import { parseDate } from './deps.ts';

const myUUID = v4.generate();
parseDate("20-05-2020", "dd-mm-yyyy")

使用这种方法时,应考虑 integrity checking & lock files:

// Add a new dependency to "src/deps.ts", used somewhere else.
export { xyz } from "https://unpkg.com/xyz-lib@v0.9.0/lib.ts";
# Create/update the lock file "lock.json".
deno cache --lock=lock.json --lock-write src/deps.ts

# Include it when committing to source control.
git add -u lock.json
git commit -m "feat: Add support for xyz using xyz-lib"
git push

为了避免在任何地方键入 https://deno.land/std/uuid/mod.ts,您可以使用 import maps

// import_map.json

{
   "imports": {
      "http/": "https://deno.land/std/http/"
   }
}
// server.ts
import { serve } from "http/server.ts";

const body = new TextEncoder().encode("Hello World\n");
for await (const req of serve(":8000")) {
  req.respond({ body });
}
deno run --importmap=import_map.json --allow-net server.ts

导入地图 目前不稳定,但您可以在 --unstable 标志后使用它们。


除此之外,通常有一个 deps.ts 文件,您可以在其中重新导出所有依赖项。

// deps.ts
export * as path from "https://deno.land/std@0.51.0/path/mod.ts";
// other exports .. from
// some other file
import { path } from './deps.ts' // instead of "https://deno.land/std@0.51.0/path/mod.ts"
path.basename('/bar/test.txt');