问题
In Deno it is possible to version the dependencies in the import statement, and there's no package.json
like with npm
.
But how to managed it's URLs and versions in a single place?
I will have multiple files and dependencies that will be declared all over my system.
For example:
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)
回答1:
To avoid typing https://deno.land/std/uuid/mod.ts
everywhere you can use 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
import maps are currently unstable, but you can use them behind --unstable
flag.
Aside from that it's common to have a deps.ts
file where you'll re-export all your dependencies.
// 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');
回答2:
In deno
there is a convention for consolidating imports into 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";
Exports can then be imported in other modules/scripts on your application:
import { v4 } from "./deps.ts";
import { parseDate } from './deps.ts';
const myUUID = v4.generate();
parseDate("20-05-2020", "dd-mm-yyyy")
When using this approach one should consider 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://stackoverflow.com/questions/61917605/how-to-manage-deno-dependencies-in-one-place