Роль артефакта dist/index.js в структуре Node-проекта

Раздел: Node.js -> Структура проекта

Каталог сборки и точка входа пакета

В большинстве Node.js проектов каталог dist содержит артефакты сборки. Файл dist/index.js выступает точкой входа для потребителей пакета или для запуска приложения. Исходники находятся в src, сборщик создает dist/index.js, а package.json указывает на этот файл через main или exports.

Типичный поток: src/index.ts -> tsc/esbuild/rollup -> dist/index.js -> require/import в другом проекте.

Базовая схема

project/
  src/
    index.ts
  dist/
    index.js
  package.json
  tsconfig.json

Dist index js (файл dist/index.js)

Пример package.json для библиотеки с CommonJS:

{
  "name": "my-lib",
  "version": "1.0.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "files": ["dist"],
  "scripts": {
    "build": "tsc"
  }
}

Index js (файлы index.js и index.html в проекте)

Пример tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "dist",
    "rootDir": "src",
    "declaration": true,
    "strict": true
  },
  "include": ["src"]
}

папка js (структура папок в javascript проекте)

После команды npm run build появляется dist/index.js. Node.js при require('my-lib') читает package.json main и загружает dist/index.js.

Как выбрать между dist/index.js и src/index.js?

Вариант с dist/index.js нужен для публикации пакета, где потребитель не должен компилировать TypeScript. src/index.js подходит для простых JS пакетов без сборки. Для TypeScript и Babel dist дает совместимость.

Что дает поле exports в package.json для dist/index.js?

exports управляет доступом к подпутям и условиями import/require. Пример:

{
  "name": "my-lib",
  "main": "dist/index.js",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "require": "./dist/index.js",
      "import": "./dist/index.mjs"
    }
  }
}

При require('my-lib') Node.js может взять require условие. При import ... берет import. Если exports отсутствует, работает main.

Как работает dist/index.js в ESM проекте?

Если package.json содержит type module, dist/index.js считается ESM. Тогда синтаксис require не работает. Для CJS нужен .cjs или type commonjs. Пример:

{
  "type": "module",
  "main": "dist/index.js"
}
// src/index.js
export function sum(a, b) {
  return a + b;
}

После сборки dist/index.js сохраняет export. Импорт: import { sum } from 'my-lib'.

Когда dist/index.js создается бандлером, а не tsc?

esbuild, rollup, webpack создают один файл dist/index.js. Это удобно для библиотек с зависимостями. Пример esbuild:

npx esbuild src/index.ts --bundle --platform=node --format=cjs --outfile=dist/index.js

Результат: один файл с кодом и зависимостями. Минус: сложнее tree-shaking для потребителя, если зависимости включены.

Как dist/index.js используется в monorepo?

В workspace каждый пакет имеет свой dist/index.js. Корневой package.json содержит workspaces. Ссылки между пакетами работают через имя пакета, а сборка выполняется по каждому пакету. Пример:

{
  "workspaces": ["packages/*"]
}
packages/
  core/
    src/index.ts
    dist/index.js
    package.json
  cli/
    src/index.ts
    dist/index.js
    package.json

Типичные проблемы

Ошибка Cannot find module 'dist/index.js'. Причина: сборка не выполнена или путь указан неверно. Решение: запуск npm run build, проверка package.json main и files.

Публикация без dist. Если files содержит только src или .npmignore исключает dist, пакет выходит без точки входа. Решение: files: ["dist"] или добавление dist в npmignore.

Несовпадение ESM и CJS. require не работает для ESM dist/index.js. Решение: exports с require/import или два файла index.cjs и index.mjs.

Неверный rootDir. tsc может создать dist/src/index.js вместо dist/index.js. Решение: rootDir: "src", outDir: "dist".

Source maps отсутствуют. Для отладки нужно sourceMap: true и declarationMap: true.

Практические сценарии с dist/index.js

Сборка TypeScript библиотеки

Структура включает src/index.ts, tsconfig.json и package.json. После сборки появляется dist/index.js и dist/index.d.ts.

Пример
// src/index.ts
export interface User {
  id: number;
  name: string;
}

export function greet(user: User): string {
  return `Hello, ${user.name}!`;
}
Пример
// package.json
{
  "name": "greet-lib",
  "version": "1.0.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "files": ["dist"],
  "scripts": {
    "build": "tsc"
  },
  "devDependencies": {
    "typescript": "^5.0.0"
  }
}
Пример
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "dist",
    "rootDir": "src",
    "declaration": true,
    "strict": true
  },
  "include": ["src"]
}
Пример
npm run build
node -e "const { greet } = require('./dist/index.js'); console.log(greet({ id: 1, name: 'Anna' }))"
Hello, Anna!

Проверка содержимого npm пакета

Команда npm pack --dry-run показывает список файлов. В выводе должен быть dist/index.js.

Пример
npm pack --dry-run
npm notice Tarball Contents
npm notice 1.2kB dist/index.js
npm notice 0.4kB dist/index.d.ts
npm notice 0.5kB package.json
npm notice Tarball Details
npm notice name: greet-lib
npm notice version: 1.0.0
npm notice filename: greet-lib-1.0.0.tgz

ESM и CJS через exports

Два файла: dist/index.cjs для require и dist/index.mjs для import. package.json связывает условия.

Пример
// src/index.ts
export function sum(a: number, b: number): number {
  return a + b;
}
Пример
// package.json
{
  "name": "math-lib",
  "version": "1.0.0",
  "main": "dist/index.cjs",
  "module": "dist/index.mjs",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "require": "./dist/index.cjs",
      "import": "./dist/index.mjs"
    }
  },
  "files": ["dist"],
  "scripts": {
    "build:cjs": "tsc -p tsconfig.cjs.json",
    "build:esm": "tsc -p tsconfig.esm.json"
  }
}
Пример
// tsconfig.cjs.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "dist",
    "declaration": false
  },
  "include": ["src"]
}
Пример
// tsconfig.esm.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "ES2020",
    "outDir": "dist/esm",
    "declaration": true
  },
  "include": ["src"]
}

Для генерации index.cjs и index.mjs часто применяются esbuild или rollup. Пример esbuild:

Пример
npx esbuild src/index.ts --bundle --platform=node --format=cjs --outfile=dist/index.cjs
npx esbuild src/index.ts --bundle --platform=node --format=esm --outfile=dist/index.mjs
Пример
node -e "const { sum } = require('./dist/index.cjs'); console.log(sum(2, 3))"
5
Пример
node --input-type=module -e "import { sum } from './dist/index.mjs'; console.log(sum(4, 6))"
10

Rollup для библиотеки

Пример
// rollup.config.mjs
import typescript from '@rollup/plugin-typescript';

export default {
  input: 'src/index.ts',
  output: [
    { file: 'dist/index.cjs', format: 'cjs', sourcemap: true },
    { file: 'dist/index.mjs', format: 'es', sourcemap: true }
  ],
  plugins: [typescript({ tsconfig: './tsconfig.json' })]
};
Пример
npx rollup -c
src/index.ts -> dist/index.cjs, dist/index.mjs...
created dist/index.cjs in 120ms
created dist/index.mjs in 118ms

Shebang для CLI

Если dist/index.js является CLI, первая строка содержит shebang. TypeScript сохраняет его при наличии в исходнике.

Пример
// src/index.ts
#!/usr/bin/env node
console.log('CLI started');
Пример
// package.json
{
  "name": "my-cli",
  "version": "1.0.0",
  "bin": {
    "my-cli": "dist/index.js"
  },
  "files": ["dist"],
  "scripts": {
    "build": "tsc"
  }
}
Пример
npm run build
node dist/index.js
CLI started

Источники карт для отладки

Пример
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "dist",
    "rootDir": "src",
    "sourceMap": true,
    "declarationMap": true,
    "declaration": true
  }
}
Пример
// src/index.ts
export function fail(): never {
  throw new Error('Debug me');
}
Пример
node --enable-source-maps dist/index.js
Error: Debug me
    at fail (/project/src/index.ts:2:9)

Монорепозиторий с workspace

Пример
// package.json
{
  "private": true,
  "workspaces": ["packages/*"]
}
Пример
// packages/core/package.json
{
  "name": "@my/core",
  "version": "1.0.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "files": ["dist"],
  "scripts": {
    "build": "tsc"
  }
}
Пример
// packages/app/src/index.ts
import { coreFn } from '@my/core';

coreFn();
Пример
npm run build --workspaces
> @my/core@1.0.0 build
> tsc

> @my/app@1.0.0 build
> tsc

Диагностика ошибки отсутствующего dist/index.js

Пример
node -e "require('greet-lib')"
Error: Cannot find module 'greet-lib'
Require stack:
- /project/test.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1075:15)

Причины: пакет не собран, main указывает на несуществующий путь, dist исключен из публикации. Проверка: ls dist, node -p "require('./package.json').main", npm pack --dry-run.

Пример
ls dist
node -p "require('./package.json').main"
npm pack --dry-run
index.js
index.d.ts
dist/index.js
... dist/index.js included

Динамический импорт dist/index.js

Пример
// test.mjs
const mod = await import('./dist/index.js');
console.log(mod.greet({ id: 2, name: 'Boris' }));
Пример
node test.mjs
Hello, Boris!

Файл dist/index.js - comments

En
Dist index js (javascript)