0
0
DenoHow-ToBeginner ยท 4 min read

How to Lock Dependencies in Deno for Secure and Stable Projects

In Deno, you lock dependencies by generating a lock.json file using deno cache --lock=lock.json --lock-write. This file records exact versions and hashes of remote modules, ensuring consistent and secure dependency usage.
๐Ÿ“

Syntax

To lock dependencies in Deno, use the deno cache command with the --lock and --lock-write flags.

  • --lock=lock.json: Specifies the lock file to use or create.
  • --lock-write: Writes the current dependency hashes to the lock file.

This command caches dependencies and records their hashes to ensure future runs use the exact same versions.

bash
deno cache --lock=lock.json --lock-write <your_script.ts>
๐Ÿ’ป

Example

This example shows how to create a lock file for a Deno script that imports a remote module. The lock file ensures the same module version and content are used every time.

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

serve(() => new Response("Hello from locked dependencies!"));
๐Ÿ“Œ

Locking the dependencies

Run this command to cache dependencies and create the lock file:

bash
deno cache --lock=lock.json --lock-write example.ts
Output
Check file lock.json created with hashes of all remote modules.
โš ๏ธ

Common Pitfalls

  • Not using --lock-write when creating the lock file will not generate or update it.
  • Running scripts without --lock=lock.json after locking dependencies ignores the lock file, risking inconsistent versions.
  • Modifying the lock file manually can cause errors or security issues.
  • Forcing updates requires regenerating the lock file with --lock-write.
bash
Wrong usage (no lock file created):
deno cache example.ts

Right usage (creates lock file):
deno cache --lock=lock.json --lock-write example.ts

Running with lock enforcement:
deno run --lock=lock.json example.ts
๐Ÿ“Š

Quick Reference

CommandPurpose
deno cache --lock=lock.json --lock-write Create or update lock file with dependency hashes
deno run --lock=lock.json Run script enforcing locked dependencies
deno cache --lock=lock.json Cache dependencies using existing lock file without updating
Remove lock.jsonForce dependency hashes to update on next lock-write
โœ…

Key Takeaways

Use deno cache --lock=lock.json --lock-write to create a lock file recording exact dependency versions.
Always run scripts with --lock=lock.json to enforce locked dependencies and ensure consistency.
Do not manually edit the lock file; regenerate it with --lock-write to update dependencies safely.
Lock files improve security by verifying module integrity and prevent unexpected changes in dependencies.