Роль артефакта dist/index.js в структуре Node-проекта
Каталог сборки и точка входа пакета
В большинстве 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.jsonDist 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!