0Pricing
Node.js Backend Development Bootcamp · درس

إعداد tsconfig لمشروعات Node الخلفية

اضبط خيارات المترجم وحل الوحدات والأسماء المستعارة للمسارات لإعداد TypeScript متين من جهة الخادم

إعداد tsconfig لمشروعات Node الخلفية درس مجاني في Node.js Backend Development Bootcamp على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Node.js Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Node.js Backend Development Bootcamp 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why tsconfig Matters on the Server

When you run TypeScript on a Node.js backend, tsconfig.json is the single source of truth that controls how your code is type-checked and compiled to JavaScript.

  • compilerOptions tune the output, strictness, and module system.
  • include / exclude decide which files are part of the project.

A backend config differs from a frontend one: there is no DOM, no bundler, and Node loads the emitted JavaScript directly. Getting these options right prevents subtle runtime crashes and broken imports.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true
  },
  "include": ["src/**/*"]
}

Picking the Right target

The target option controls which JavaScript version the compiler emits. On a backend you are not constrained by old browsers, only by your Node.js runtime.

  • Node 18 supports up to ES2022; Node 20+ supports ES2023.
  • A modern target means features like top-level await, class fields, and Array.at() compile to native code instead of bulky polyfills.

Match target to the lowest Node version you deploy to. Setting it too high can emit syntax your runtime cannot parse.

// Works natively when target is ES2022 on Node 18+
const nums = [10, 20, 30];
console.log(nums.at(-1)); // 30

class Cache {
  store = new Map(); // class field
  set(k, v) { this.store.set(k, v); return this; }
}
console.log(new Cache().set("a", 1).store.get("a")); // 1

module and moduleResolution

These two options decide how import and require statements are emitted and resolved.

  • module: what kind of module syntax the compiler emits.
  • moduleResolution: how TypeScript finds the files behind each import specifier.

For modern Node backends, "module": "NodeNext" with "moduleResolution": "NodeNext" is the recommended pair. It teaches TypeScript to respect Node's real resolution rules, including the type field in package.json and the difference between CommonJS and ESM.

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext"
  }
}

CommonJS vs ESM Decision

The single biggest decision for a Node backend is the module system. It is driven by the type field in package.json, not by tsconfig alone.

  • "type": "commonjs" (or omitted): files use require / module.exports.
  • "type": "module": files are ESM and use import / export.

With ESM you gain top-level await and a single import syntax, but you must write explicit file extensions in relative imports. With CommonJS you get broader compatibility with older libraries. Choose ESM for new projects unless a dependency forces CommonJS.

{
  "name": "my-api",
  "type": "module",
  "main": "dist/index.js"
}

ESM Needs File Extensions

This trips up almost everyone moving to ESM. When module is NodeNext and your package is "type": "module", relative imports in your source must include the .js extension, even though the file on disk ends in .ts.

TypeScript does not rewrite import paths, so the specifier you write is exactly what Node receives at runtime. You write .js because that is the file that will exist after compilation.

// src/user.service.ts
export function findUser(id) {
  return { id, name: "Ada" };
}

// src/index.ts  -- note the .js extension on a .ts file
import { findUser } from "./user.service.js";
console.log(findUser(7));

Turn On strict Mode

"strict": true is the most valuable option for backend reliability. It is an umbrella that enables a family of checks at once.

  • strictNullChecks: null and undefined are no longer assignable everywhere, catching missing-value bugs.
  • noImplicitAny: every value must have a known or inferable type.
  • strictFunctionTypes, strictBindCallApply, and more.

On a server these checks prevent whole classes of production crashes, like reading a property off an object that could be undefined.

function getPort(env) {
  // With strictNullChecks, env.PORT is string | undefined
  const raw = env.PORT;
  const port = raw ? Number(raw) : 3000;
  return port;
}
console.log(getPort({ PORT: "8081" })); // 8081
console.log(getPort({}));               // 3000

outDir, rootDir, and the Build Layout

These options keep your compiled output cleanly separated from your source.

  • rootDir: the base folder of your input files, usually src.
  • outDir: where emitted JavaScript lands, usually dist.

Setting rootDir guarantees the directory structure under src is mirrored exactly under dist. Without it, TypeScript infers the root from your files and a stray file outside src can shift the whole output tree, breaking your main path.

{
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "dist",
    "sourceMap": true,
    "declaration": false
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Path Aliases with baseUrl and paths

Deep relative imports like ../../../config/db are fragile. Path aliases let you write stable, readable specifiers.

  • baseUrl: the directory from which non-relative imports are resolved.
  • paths: a map of alias patterns to real folders.

A common convention is to map @/* to src/*, so any module can import from @/services/user.service.js regardless of its own depth.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

Aliases Don't Exist at Runtime

Here is the critical gotcha: paths only affects type-checking. The TypeScript compiler does not rewrite @/services/user.service.js into a real relative path in the emitted JavaScript.

So Node will fail at runtime with a module-not-found error unless you bridge the gap. Common solutions:

  • A runtime resolver like tsconfig-paths (CommonJS) or a loader.
  • A bundler such as tsup or esbuild that inlines the aliases.
  • A post-build step that rewrites the paths.

Always remember: tsconfig describes types; the runtime needs its own plan for aliases.

Node Types and Speeding Up Builds

To use globals like process, Buffer, and the fs module with full typing, install @types/node and let TypeScript pick them up.

  • types: restrict which global type packages are included (for example, just ["node"]).
  • skipLibCheck: skip type-checking of .d.ts files in dependencies, dramatically cutting build time.
  • esModuleInterop: lets you write import express from "express" for CommonJS default exports.
{
  "compilerOptions": {
    "types": ["node"],
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  }
}

A Complete Backend tsconfig

Putting it all together, here is a robust starting point for a modern ESM Node.js backend. It compiles src to dist, enforces strictness, and uses Node-native resolution.

Pair this with "type": "module" in package.json and a build script of tsc -p tsconfig.json. Remember to handle path aliases at runtime if you enable paths.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "types": ["node"],
    "baseUrl": ".",
    "paths": { "@/*": ["src/*"] }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Quick Check

Test your understanding of path aliases in a Node backend build.

Recap

You now know how to configure tsconfig.json for a server-side TypeScript project.

  • target: match your lowest Node version (ES2022 for Node 18+).
  • module / moduleResolution: use NodeNext for honest Node resolution.
  • type field in package.json drives CommonJS vs ESM; ESM relative imports need .js extensions.
  • strict: turn it on to catch null and any bugs before production.
  • rootDir / outDir: keep a clean src to dist build layout.
  • paths: great for readability, but aliases must be resolved at runtime by a loader or bundler.

With these options dialed in, your Node backend gets reliable type safety and a predictable build.

الأسئلة الشائعة

هل درس «إعداد tsconfig لمشروعات Node الخلفية» مجاني؟

نعم — نص درس «إعداد tsconfig لمشروعات Node الخلفية» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Node.js Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة Node.js Backend Development Bootcamp 4 دروس في المجموع.

ماذا ستتعلم في «إعداد tsconfig لمشروعات Node الخلفية»؟

اضبط خيارات المترجم وحل الوحدات والأسماء المستعارة للمسارات لإعداد TypeScript متين من جهة الخادم تتمرن على Node.js Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Node.js Backend Development Bootcamp؟

لا تُشترط خبرة سابقة. Node.js Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «إعداد tsconfig لمشروعات Node الخلفية»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Node.js Backend Development Bootcamp هذا؟

نعم. كل درس في Node.js Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. الترحيل من CommonJS إلى وحدات ES الأصلية
  2. إعداد tsconfig لمشروعات Node الخلفية
  3. إعداد البيئة الآمن من حيث النوع والتحقق وقت التشغيل
  4. التكرار السريع باستخدام tsx وإعادة التحميل الفوري وخرائط المصدر
← العودة إلى Node.js Backend Development Bootcamp