التبعيات ليست سحراً: إنها سلسلة توريد برمجية قابلة لإعادة الإنتاج بدقة. حد معماري حاسم: package.json != lockfile != node_modules. لا تخلط أبداً بين النية المصرح بها والواقع المحلول.
🔗 أوراق غش ذات صلة: مرجع package.json · أوامر npm · أوامر Yarn · أساسيات Node.js
1. النموذج الذهني لسلسلة توريد التبعيات المكون من 5 مراحل
في هندسة Node.js الحديثة، تمر التبعيات عبر خمس مراحل حتمية من التصريح إلى التشغيل في الإنتاج:
flowchart LR
A["① Intent Declaration<br><b>package.json</b><br>(Declared Boundaries)"] --> B["② Resolved Fact<br><b>lockfile</b><br>(Exact Version & Integrity)"]
B --> C["③ Package Manager<br><b>npm / pnpm</b><br>(Topology & Resolution)"]
C --> D["④ Physical Material<br><b>node_modules</b><br>(Disk Files & Symlinks)"]
D --> E["⑤ Consumer Execution<br><b>Build / Dev / CI</b><br>(Bundling & Artifacts)"]
classDef stage fill:#f0f7ff,stroke:#0969da,stroke-width:1px,color:#1f2328;
class A,B,C,D,E stage;
| Stage | Artifact / Medium | Core Role & Reality | Typical Failure Mode & Pitfall |
|---|---|---|---|
| ① Intent | package.json |
Declares what the application intends to use with loose SemVer ranges | Overly broad wildcards (*), mixing dev and runtime deps, unpinned engines |
| ② Resolved Fact | package-lock.json / pnpm-lock.yaml |
Records exact resolved versions, download source URL, and SHA-512 cryptographic integrity hash | Lockfile missing from git, cross-team manager divergence causing lock churn |
| ③ Tooling | npm / pnpm / yarn |
Resolves conflict graph, executes downloads, and constructs disk directory structures | Inconsistent CLI commands across dev and CI (e.g. running npm i in CI) |
| ④ Material | node_modules |
Physical code files accessed by Node.js runtime and bundler module resolution algorithms | Phantom dependencies, duplicate packages (doppelgangers), disk exhaustion |
| ⑤ Execution | scripts (build / test / start) |
Tooling consumes material to compile, run tests, and emit deployable containers/artifacts | Implicit OS assumptions, unverified lifecycle scripts (preinstall attacks) |
2. المرحلة 1: التصريح بالنية (package.json)
package.json defines project dependencies. Understanding dependency scopes and SemVer ranges is essential for reproducible builds.
2.1 Dependency Scopes & Runtime Isolation
{
"dependencies": {
"react": "^19.0.0"
},
"devDependencies": {
"typescript": "^5.7.0",
"vite": "^6.0.0"
},
"peerDependencies": {
"react": ">=18.0.0"
},
"optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "4.28.0"
}
}
| Field | Target Environment | Usage & Bundling Behavior | Production Container (--omit=dev) |
|---|---|---|---|
dependencies |
Production & Dev | Runtime requirements (e.g. Express, React, Lodash) | Installed |
devDependencies |
Local dev & CI build | Compilers, linters, test runners (Vite, TypeScript, Vitest, ESLint) | Skipped (significantly reduces container image size) |
peerDependencies |
Host application runtime | Plugins requiring a compatible host version (e.g. React component libraries) | npm v7+ installs automatically; pnpm warns strictly unless configured |
optionalDependencies |
Conditional runtime | Platform-specific native binaries (e.g. Rollup / esbuild native bindings) | Attempted; install failures are safely ignored |
2.2 Semantic Versioning (SemVer) Range Reference
| Syntax | Semantic Meaning | Example | Permitted Resolved Range | Risk Assessment |
|---|---|---|---|---|
1.2.3 |
Exact Pin | 1.2.3 |
Only 1.2.3 |
Zero drift; maximum determinism |
^1.2.3 |
Compatible Minor | ^1.2.3 |
>=1.2.3 <2.0.0 (locks major) |
Standard default; risky if a dependency violates SemVer |
~1.2.3 |
Compatible Patch | ~1.2.3 |
>=1.2.3 <1.3.0 (locks minor) |
Recommended for high-stability production services |
* / latest |
Wildcard Any | * |
Resolves to newest release | Critical Danger: strictly prohibited in production |
workspace:* |
Monorepo Protocol | workspace:^ |
Points to local package in repo | pnpm / Yarn protocol; replaced with exact version on publish |
2.3 Runtime & Package Manager Pinning
Lock engines and package managers in the root package.json to prevent team members and CI agents from running unintended tools:
{
"engines": {
"node": ">=20.18.0",
"pnpm": ">=9.15.0"
},
"packageManager": "pnpm@9.15.4"
}
Tip (Corepack): Node.js 16.9+ bundles
corepack. Enabling it (corepack enable) automatically intercepts invocations and enforces the exact package manager version declared inpackageManager.
3. المرحلة 2: الحقيقة المحلولة (lockfile)
A lockfile is the mathematical solution to the dependency tree at a frozen point in time.
3.1 Why Lockfiles Must Never Be Ignored
package.jsonspecifies ranges (^), not concrete versions. Without a lockfile, two builds on separate days can install divergent code.- Transitive dependencies (dependencies of dependencies) define their own ranges and update silently.
- Lockfiles guarantee three immutable facts:
- Exact Version (
version): The exact resolved release number. - Immutable Origin (
resolved): Direct cryptographic URL to the registry tarball. - Cryptographic Integrity (
integrity): SHA-512 cryptographic hash preventing man-in-the-middle tampering.
- Exact Version (
3.2 Lockfile Format Comparison
| Lockfile | Tool | Format | Storage Strategy | Key Characteristics |
|---|---|---|---|---|
package-lock.json |
npm (v7+) | JSON | packages["node_modules/xyz"] path map |
Exhaustive physical tree mapping; large file size but high transparency |
pnpm-lock.yaml |
pnpm (v9) | YAML | Snapshots: importers and packages |
Content-addressable snapshot format; highly readable with easy merge conflict resolution |
yarn.lock |
Yarn (v1/v4) | Custom / YAML | Resolution descriptor mappings | Maps requested version ranges to resolved packages; requires installer to reconstruct disk tree |
4. المرحلة 3: طبولوجيا مديري الحزم (npm مقابل pnpm)
The fundamental distinction between package managers lies in how they structure the node_modules directory on disk.
flowchart TD
subgraph S_NPM ["npm / Yarn v1: Hoisting Topology (Flat)"]
N_Root["node_modules/"]
N_A["A (v1.0 - Direct Dependency)"]
N_B["B (v1.0 - Transitive Hoisted)"]
N_Root --> N_A
N_Root --> N_B
N_Notice["⚠️ Code can directly import B, creating a Phantom Dependency"]
end
subgraph S_PNPM ["pnpm: Content-Addressable & Symlink Topology"]
P_Root["node_modules/"]
P_A["A (Symlink -> .pnpm/A@1.0/...)"]
P_Dot[".pnpm/ (Isolated Virtual Store)"]
P_Root --> P_A
P_Root --> P_Dot
P_Ok["✅ App can only import declared dependency A; B is strictly isolated"]
end
npm v3+ Flattening (Hoisting): Moves transitive dependencies to the root
node_modules/to prevent deep Windows path length errors.- Flaw 1: Phantom Dependencies: If project depends on
A, andAdepends onB, npm hoistsBto the root. Application code canimport 'B'without declaring it inpackage.json. IfAlater dropsB, the build breaks unpredictably in CI. - Flaw 2: Doppelgangers: When two libraries require conflicting versions of
X(X@1andX@2), hoisting fails for one version, forcing nested duplicates on disk.
- Flaw 1: Phantom Dependencies: If project depends on
pnpm Content-Addressable Storage (CAS) & Symlinks:
- All package tarballs are unpacked once into a global store (
~/.local/share/pnpm/store). Every project hard-links to this store, using zero additional disk space. - Root
node_modules/contains only symlinks to packages declared directly inpackage.json. - Transitive dependencies are nested under
.pnpm/, making them completely inaccessible to application code and permanently eliminating phantom dependencies.
- All package tarballs are unpacked once into a global store (
4.1 Feature & Performance Decision Matrix
| Evaluation Criteria | npm (v10+) | pnpm (v9+) | Yarn (v1 Classic) |
|---|---|---|---|
| Installation Speed | Moderate (extracts full tarballs per project) | Fastest (instant hard links from global CAS) | Slow |
| Disk Consumption | Linear growth per project / branch | Minimal (global deduplication across all repos) | Linear growth per project |
| Phantom Dependency Protection | ❌ None (hoisting leaks transitive packages) | Strict (only declared deps are accessible) | ❌ None |
| Monorepo Workspace Support | Basic workspaces |
Industry Standard (advanced filters, parallel runs) | Basic |
| Learning Curve & Ecosystem | Zero barrier (bundled with Node.js) | Low (drop-in command parity with npm) | Low |
5. المرحلة 4: مرجع الأوامر اليومية عالية التردد
| Action / Scenario | npm Command | pnpm Command | Usage Notes & Best Practices |
|---|---|---|---|
| Dev Environment Install | npm install |
pnpm install |
Installs or updates dependencies according to lockfile |
| CI/CD Immutable Install | npm ci |
pnpm install --frozen-lockfile |
CI Required: fails immediately if lockfile does not match package.json |
| Production Container Install | npm install --omit=dev |
pnpm install --prod |
Skips devDependencies, drastically reducing Docker image size |
| Add Runtime Dependency | npm i <pkg> |
pnpm add <pkg> |
Appends to dependencies and updates lockfile |
| Add Dev Dependency | npm i -D <pkg> |
pnpm add -D <pkg> |
Appends to devDependencies |
| Add Exact Version | npm i -E <pkg> |
pnpm add -E <pkg> |
Installs without ^ or ~, pinning exact version number |
| Remove Dependency | npm uninstall <pkg> |
pnpm remove <pkg> |
Removes package files and prunes lockfile entries |
| Inspect Dependency Origin | npm ls <pkg> |
pnpm why <pkg> |
Traces why a transitive package is installed (vital for debugging) |
| Vulnerability Audit | npm audit / npm audit fix |
pnpm audit / pnpm audit --fix |
Scans advisory databases for known CVEs |
| Prune Local Cache/Store | npm cache clean --force |
pnpm store prune |
Removes unreferenced packages from the local store/cache |
6. المرحلة 5: خطوط أنابيب CI/CD القابلة للتكرار وقائمة التحقق
6.1 Production .npmrc Best Practices
Commit a root .npmrc file to enforce strict consistency across local workstations and CI environments:
registry=https://registry.npmjs.org/
engine-strict=true
strict-peer-dependencies=true
6.2 Standard GitHub Actions Workflow (pnpm)
name: CI & Build Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Setup Node.js & Cache
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'pnpm'
- name: Immutable Dependency Installation
run: pnpm install --frozen-lockfile
- name: Lint & Typecheck
run: |
pnpm run lint
pnpm run type-check
- name: Automated Tests
run: pnpm test
- name: Production Build
run: pnpm run build
6.3 Reproducible Build Verification Checklist
- Is the lockfile tracked in Git? Verify that
.gitignoredoes not excludepackage-lock.jsonorpnpm-lock.yaml. - Are CI pipelines using immutable install commands? Never run
npm installin CI; enforcenpm ciorpnpm install --frozen-lockfile. - Are phantom dependencies eliminated? Verify that all imported packages exist in root
package.json. Runpnpm why <pkg>if a module fails to resolve. - Is the Node.js runtime pinned? Align local dev and CI machines via
.nvmrcor.node-version. - Are lifecycle scripts audited? Prevent supply-chain malware by auditing
preinstall/postinstallscripts; use--ignore-scriptsin untrusted contexts.