TSConfig Path Aliases Module Resolution

Configure TypeScript path aliases for clean internal imports, wire runtime resolvers for each target, and ban deep relative chains.

TypescriptConfig Management

Code

typescriptsnippet
32 lines
// tsconfig.json 局部:
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@/features/*": ["features/*"],
      "@/shared/*": ["shared/*"],
      "@/config": ["config/index.ts"]
    }
  }
}

// src/config/index.ts —— 显式环境分层
export const config = {
  port: Number(process.env.PORT ?? 3000),
  logLevel: process.env.LOG_LEVEL ?? 'info',
} as const;

// src/features/orders/service.ts —— 别名导入取代 ../../../
import { config } from '@/config';
import { logger } from '@/shared/logger';

export async function listOrders(page: number) {
  logger.debug('listing orders page', page, 'port', config.port);
  return [{ id: 1, total: 42 }];
}

// 打包器(如 esbuild)注册解析器:
// esbuild src/index.ts --bundle //   --alias:@/features=./src/features //   --alias:@/shared=./src/shared //   --alias:@/config=./src/config/index.ts

const orders = await listOrders(1);
console.log('orders:', orders.length);

Inside the snippet

TSConfig Path Aliases Module Resolution keeps everything in the function listOrders.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. From @/config it pulls config, logger — the imports name exactly which library surface the snippet touches.

Configuration comes from the environment — it reads PORT, LOG_LEVEL, so the same code switches behavior between environments without edits.

A fresh value is allocated for the result; the arguments stay untouched.

Caveats

  • External dependency: @/config and @/shared/logger — install them before running the snippet.

Putting it to use

The main signature reads export const config =

Each step the file takes shows up labeled in the output: orders:.

The surface worth importing is config; the helpers around it are private to the snippet.

Core lines

const orders = await listOrders(1);
return [{ id: 1, total: 42 }];

Interactive Tools for This Topic

FAQ

Does `config` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Which packages must be installed first?
Yes. The imports resolve to `@/config` and `@/shared/logger`, which the package manager must provide.