### Install pkgbld with npm
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command installs pkgbld as a development dependency using npm. Ensure you have npm installed and configured on your system.
```bash
npm install --save-dev pkgbld
```
--------------------------------
### Install and Use pkgbld Build Tool
Source: https://context7.com/kshutkin/package-build/llms.txt
Demonstrates how to install and use the pkgbld build tool for TypeScript/JavaScript libraries. It covers basic builds, multi-format builds with UMD and compression, and custom output configurations. pkgbld simplifies Rollup configuration and supports features like source maps and custom entry points.
```bash
# Install
npm install --save-dev pkgbld
# Basic build - outputs ES and CommonJS by default
npx pkgbld
# Multi-format build with UMD and compression
npx pkgbld --formats=es,cjs --umd=index --compress=umd
# Build with source maps for all formats
npx pkgbld --sourcemaps=es,cjs,umd
# Custom output directory and entry point compression
npx pkgbld --dest=build --src=lib --compress=es,umd
```
--------------------------------
### Monorepo Structure Example
Source: https://context7.com/kshutkin/package-build/llms.txt
Illustrates a typical monorepo directory structure using pnpm workspaces. It includes a root package.json, pnpm-workspace.yaml, and sub-packages organized within the 'packages' directory.
```tree
workspace-root/
├── pnpm-workspace.yaml
├── package.json
└── packages/
├── core/
│ ├── package.json
│ └── src/
├── utils/
│ ├── package.json
│ └── src/
└── plugins/
├── package.json
└── src/
```
--------------------------------
### Initializing a new pkgbld project (Bash)
Source: https://context7.com/kshutkin/package-build/llms.txt
This bash command initiates the interactive scaffolding process for a new project using `create-pkgbld`. This tool guides users through configuration, setting up the project structure and initial build settings.
```bash
# Create new project interactively
npm init pkgbld
```
--------------------------------
### Build the Monorepo Workspace
Source: https://context7.com/kshutkin/package-build/llms.txt
Command to initiate the build process for all packages in the monorepo using pnpm's recursive script execution. Shows example output indicating build times per package.
```bash
# From root directory
pnpm build
# Output:
# @workspace/utils: Built in 120ms
# @workspace/core: Built in 180ms
# @workspace/plugins: Built in 95ms
```
--------------------------------
### Install and Use TypeScript Declaration Bundling Plugin (Bash)
Source: https://context7.com/kshutkin/package-build/llms.txt
This snippet shows how to install and use the 'pkgbld-plugin-dts-buddy' to automatically bundle TypeScript declaration files. After installation, running 'npx pkgbld' will trigger the plugin, consolidating all '.d.ts' files into a single output file within the 'dist' directory. This simplifies type management in projects.
```bash
# Install plugin
npm install --save-dev pkgbld-plugin-dts-buddy
# Build (plugin auto-discovered and loaded)
npx pkgbld
```
--------------------------------
### Prune with 'library' profile
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command prunes package.json using the 'library' profile, which is the default. It retains essential scripts for library development and maintenance, such as 'preinstall', 'install', 'postinstall', etc.
```bash
pkgbld prune --profile=library
```
--------------------------------
### Build Command with External Dependency Bundling
Source: https://context7.com/kshutkin/package-build/llms.txt
Example build command using pkgbld that specifies both output formats (ES, CJS) and explicitly includes 'lodash' and 'date-fns' as bundled external dependencies.
```bash
npx pkgbld --formats=es,cjs --include-externals=lodash,date-fns
```
--------------------------------
### Install cli-test-helper using npm
Source: https://github.com/kshutkin/package-build/blob/main/cli-test-helper/README.md
This snippet shows how to install the cli-test-helper package as a development dependency using npm. It's typically used in projects that involve testing command-line tools.
```sh
npm install --save-dev cli-test-helper
```
--------------------------------
### Install pkgbld-internal Dev Dependency
Source: https://context7.com/kshutkin/package-build/llms.txt
Installs the 'pkgbld-internal' package as a development dependency in the workspace. This command is typically run from the project's root directory.
```bash
npm install --save-dev pkgbld-internal
```
--------------------------------
### Production Build Output (dist/index.mjs)
Source: https://context7.com/kshutkin/package-build/llms.txt
Example of the JavaScript output after a production build using pkgbld with preprocessing. Debug and test-specific code blocks are removed based on the defined build context.
```javascript
// DEBUG and development code removed
export function processData(data) {
const result = data.toUpperCase();
return result.trim();
}
// __testOnly functions removed
```
--------------------------------
### Prune with 'app' profile
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command prunes package.json using the 'app' profile, which includes additional retained scripts relevant for application development ('start', 'test', etc.) on top of the 'library' profile scripts.
```bash
pkgbld prune --profile=app
```
--------------------------------
### Browser Usage of Multiple UMD Builds
Source: https://context7.com/kshutkin/package-build/llms.txt
This HTML example demonstrates how to include multiple UMD builds of a library in a browser environment. It shows loading the UMD bundles via CDN and accessing their functionalities through the custom global variables defined in the package.json configuration.
```html
```
--------------------------------
### Example Bundled TypeScript Declarations (TypeScript)
Source: https://context7.com/kshutkin/package-build/llms.txt
This TypeScript code illustrates the content of a bundled declaration file generated by 'pkgbld-plugin-dts-buddy'. It shows how types and exports from multiple source files (e.g., './utils/array', './utils/string', './types') are combined into a single 'index.d.ts' file, including interfaces and function declarations.
```typescript
// Bundled by dts-buddy
export { processArray, filterArray } from './utils/array';
export { capitalize, slugify } from './utils/string';
export type { User, Config } from './types';
export interface User {
id: string;
name: string;
email: string;
}
export interface Config {
apiUrl: string;
timeout: number;
}
export declare function processArray(arr: T[]): T[];
export declare function filterArray(arr: T[], predicate: (item: T) => boolean): T[];
export declare function capitalize(str: string): string;
export declare function slugify(str: string): string;
```
--------------------------------
### TypeScript Source with Preprocessing Directives
Source: https://context7.com/kshutkin/package-build/llms.txt
Example of a TypeScript file demonstrating conditional compilation using pkgbld's preprocessing directives like '@if DEBUG' and '@if ENVIRONMENT'. This allows for environment-specific code inclusion.
```typescript
// @if DEBUG
import { debugLogger } from './debug';
// @endif
export function processData(data: string): string {
// @if DEBUG
debugLogger.log('Processing data:', data);
// @endif
const result = data.toUpperCase();
// @if ENVIRONMENT='production'
return result.trim();
// @endif
// @if ENVIRONMENT='development'
console.log('Development mode:', result);
return result;
// @endif
}
// @if NODE_ENV='test'
export function __testOnly_resetState() {
// Test utilities only in test builds
}
// @endif
```
--------------------------------
### Disable 'pack' script setup
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This flag prevents pkgbld from automatically adding or managing the 'pack' script in your package.json file. This is useful if you handle packaging manually or use a different workflow.
```bash
pkgbld --no-pack
```
--------------------------------
### pkgbld Build Tool: package.json Configuration
Source: https://context7.com/kshutkin/package-build/llms.txt
Shows how to configure the pkgbld build tool within a project's package.json file. This includes defining build scripts and specifying package exports for different module formats. The example illustrates how pkgbld automatically updates package.json after a build.
```json
{
"name": "my-library",
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "pkgbld --formats=es,cjs --umd=index --compress=umd",
"prepack": "pkgbld prune"
},
"exports": {
".": "./src/index.ts",
"./utils": "./src/utils.ts",
"./react": "./src/react.tsx"
}
}
```
--------------------------------
### Updated package.json after Bundling Dependencies
Source: https://context7.com/kshutkin/package-build/llms.txt
Shows how the package.json might be updated after a build process that bundles certain dependencies. In this example, 'lodash' and 'date-fns' are moved from 'dependencies' to 'devDependencies', indicating they are bundled and not runtime requirements.
```json
{
"dependencies": {
"react": "^18.2.0"
},
"devDependencies": {
"lodash": "^4.17.21",
"date-fns": "^2.30.0"
}
}
```
--------------------------------
### Initialize and Configure Package with pkgbld
Source: https://context7.com/kshutkin/package-build/llms.txt
Command to initialize a new package project using pkgbld and the interactive prompts for configuration. This process generates essential files like package.json and tsconfig.json for building and managing the package. It supports defining output and source directories, formats, and compression options.
```bash
npm init pkgbld my-awesome-lib
cd my-awesome-lib
```
--------------------------------
### Specify executable file
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option designates a file (e.g., './dist/index.cjs') to be made executable. The first file specified will be added to the 'bin' field in package.json.
```bash
pkgbld --bin=./dist/index.cjs
```
--------------------------------
### Enable Preprocessing for Specific Entry Points
Source: https://context7.com/kshutkin/package-build/llms.txt
Command to enable preprocessing for 'index' and 'worker' entry points when building with pkgbld. Supports multiple formats like ES and CommonJS.
```bash
npx pkgbld --preprocess=index,worker --formats=es,cjs
```
--------------------------------
### Preprocess entry point 'index'
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option enables preprocessing for the specified entry point ('index') using 'rollup-plugin-preprocess'. The preprocessor injects variables like 'es', 'cjs', or 'umd' based on the target format.
```bash
pkgbld --preprocess=index
```
--------------------------------
### pkgbld Prune: package.json Before and After
Source: https://context7.com/kshutkin/package-build/llms.txt
Compares a project's package.json file before and after running the `pkgbld prune` command. The 'before' state includes development dependencies and scripts, while the 'after' state shows a cleaner version suitable for publishing, with only production dependencies and essential scripts.
```json
{
"name": "my-lib",
"version": "1.0.0",
"main": "./dist/index.cjs",
"scripts": {
"build": "pkgbld",
"test": "vitest",
"lint": "eslint src",
"prepack": "npm run build && pkgbld prune"
},
"devDependencies": {
"pkgbld": "^1.0.0",
"typescript": "^5.0.0",
"vitest": "^1.0.0",
"eslint": "^8.0.0"
},
"dependencies": {
"lodash": "^4.17.21"
}
}
```
```json
{
"name": "my-lib",
"version": "1.0.0",
"main": "./dist/index.cjs",
"scripts": {
"prepack": "npm run build && pkgbld prune"
},
"dependencies": {
"lodash": "^4.17.21"
}
}
```
--------------------------------
### Utils Package package.json Build and Prepack Scripts
Source: https://context7.com/kshutkin/package-build/llms.txt
package.json for the '@workspace/utils' package. The 'build' script uses 'pkgbld-internal' for ES format compilation, and 'prepack' runs 'pkgbld-internal prune'.
```json
{
"name": "@workspace/utils",
"version": "1.0.0",
"scripts": {
"build": "pkgbld-internal --formats=es",
"prepack": "pkgbld-internal prune"
}
}
```
--------------------------------
### Build UMD bundles for specific entry points
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This CLI command instructs pkgbld to compile specified entry points (e.g., 'index', 'core') into UMD (Universal Module Definition) format. If the 'umd' field is defined in package.json, it defaults to 'index'.
```bash
pkgbld --umd=index,core
```
--------------------------------
### Test CLI Builds with File System Simulation (JavaScript)
Source: https://context7.com/kshutkin/package-build/llms.txt
This snippet demonstrates using 'cli-test-helper' to simulate file system operations for testing CLI build tools. It converts string representations of file structures into actual files and vice versa, allowing for isolated and reproducible tests. Dependencies include 'cli-test-helper', 'node:child_process', 'node:util', 'node:assert', 'node:fs/promises', 'node:os', and 'node:path'.
```javascript
// test/build.test.js
import { stringToFiles, filesToString } from 'cli-test-helper';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import assert from 'node:assert';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const execAsync = promisify(exec);
describe('pkgbld build', () => {
let testDir;
beforeEach(async () => {
testDir = await mkdtemp(join(tmpdir(), 'test-'));
});
afterEach(async () => {
await rm(testDir, { recursive: true, force: true });
});
it('builds TypeScript to ES modules', async () => {
// Define test input as string
const testInput = `
package.json
|{
| "name": "test-lib",
| "type": "module",
| "scripts": { "build": "pkgbld" }
|}
src
index.ts
|export const greet = (name: string) => `Hello, ${name}!`;
|export const add = (a: number, b: number) => a + b;
`;
// Create test files from string
await stringToFiles(testInput, testDir);
// Run build
await execAsync('npm run build', { cwd: testDir });
// Capture output as string
const output = await filesToString(testDir, ['node_modules']);
// Verify output contains expected files
assert.match(output, /dist/);
assert.match(output, /index\.mjs/);
assert.match(output, /index\.d\.ts/);
});
it('handles multiple entry points', async () => {
const testInput = `
package.json
|{
| "name": "multi-entry",
| "exports": {
| ".": "./src/index.ts",
| "./utils": "./src/utils.ts"
| }
|}
src
index.ts
|export { add, subtract } from './utils';
utils.ts
|export const add = (a: number, b: number) => a + b;
|export const subtract = (a: number, b: number) => a - b;
`;
await stringToFiles(testInput, testDir);
await execAsync('npx pkgbld', { cwd: testDir });
const output = await filesToString(testDir, ['node_modules']);
// Verify both entry points built
assert.match(output, /dist\/index\.mjs/);
assert.match(output, /dist\/utils\.mjs/);
});
});
```
--------------------------------
### Format package.json file
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command formats the package.json file, ensuring consistent indentation and key ordering. This helps maintain readability and manageability of your project's metadata.
```bash
pkgbld --format-package-json
```
--------------------------------
### Integrating xc6 into package.json Scripts
Source: https://context7.com/kshutkin/package-build/llms.txt
Shows how to incorporate 'xc6' commands into the 'scripts' section of 'package.json'. This allows for automating build-related tasks like cleaning output directories, copying assets, and preparing the package for distribution, ensuring cross-platform consistency.
```json
{
"scripts": {
"clean": "xc6 rm dist",
"prebuild": "xc6 rm dist",
"postbuild": "xc6 cp README.md dist/ && xc6 cp LICENSE dist/",
"prepare": "xc6 rm .cache && xc6 rm coverage"
}
}
```
--------------------------------
### xc6 vs. Platform-Specific Commands
Source: https://context7.com/kshutkin/package-build/llms.txt
Compares the use of 'xc6' for cross-platform compatibility against traditional platform-specific commands (like 'rm -rf' for Unix and 'rmdir' for Windows). It highlights 'xc6 rm' as a unified solution for cleaning directories across different operating systems.
```json
{
"scripts": {
"clean:unix": "rm -rf dist",
"clean:windows": "rmdir /s /q dist",
"clean:cross-platform": "xc6 rm dist"
}
}
```
--------------------------------
### Build only ES and CJS formats
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command specifies the output formats for the build process, limiting it to 'es' (ECMAScript modules) and 'cjs' (CommonJS). The 'umd' flag must be used separately to include UMD format.
```bash
pkgbld --formats=es
```
--------------------------------
### Configure build script in package.json
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This JSON configuration adds a 'build' script to your package.json file, allowing you to run pkgbld with the command 'npm run build'. This is a standard way to define build processes in Node.js projects.
```json
{
"scripts": {
"build": "pkgbld"
}
}
```
--------------------------------
### Cross-Platform File Operations with xc6 CLI
Source: https://context7.com/kshutkin/package-build/llms.txt
Demonstrates the usage of 'xc6', a cross-platform command-line utility for common file operations. This includes removing files/directories, copying, moving, and creating hard links, offering a unified interface across different operating systems.
```bash
# Remove files or directories
npx xc6 rm dist
npx xc6 rm node_modules
# Copy files or directories
npx xc6 cp src/templates dist/templates
npx xc6 cp README.md dist/README.md
# Move files or directories
npx xc6 mv old-name new-name
npx xc6 mv src/deprecated src/legacy
# Create hard links
npx xc6 ln dist/index.js index.js
```
--------------------------------
### Build with Different Preprocessing Contexts
Source: https://context7.com/kshutkin/package-build/llms.txt
JSON configuration for build scripts in package.json that utilize pkgbld's preprocessing feature. It shows how to set contexts like DEBUG, ENVIRONMENT, and NODE_ENV for development, production, and testing builds.
```json
{
"scripts": {
"build:dev": "pkgbld --preprocess=index --context DEBUG=true,ENVIRONMENT=development",
"build:prod": "pkgbld --preprocess=index --context DEBUG=false,ENVIRONMENT=production",
"build:test": "pkgbld --preprocess=index --context NODE_ENV=test,DEBUG=true"
}
}
```
--------------------------------
### Bundle All External Dependencies (with caution)
Source: https://context7.com/kshutkin/package-build/llms.txt
Command to bundle all external dependencies. This is generally discouraged as it can significantly increase the size of the output bundle. Use with caution and only when necessary.
```bash
npx pkgbld --include-externals=true
```
--------------------------------
### Root package.json for Monorepo
Source: https://context7.com/kshutkin/package-build/llms.txt
The main package.json file for the monorepo root. It defines common scripts like 'build' and 'clean' that operate recursively across all packages, and lists 'pkgbld-internal' as a dev dependency.
```json
{
"name": "my-workspace",
"private": true,
"scripts": {
"build": "pnpm --recursive run build",
"clean": "pnpm --recursive run clean"
},
"devDependencies": {
"pkgbld-internal": "^1.0.0"
}
}
```
--------------------------------
### Set source directory to 'src'
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option defines the directory where pkgbld should look for source files. The default is typically 'src'.
```bash
pkgbld --src=src
```
--------------------------------
### String to Filesystem Conversion
Source: https://github.com/kshutkin/package-build/blob/main/cli-test-helper/README.md
Converts a string representation of files and directories into actual files and directories in the specified base directory.
```APIDOC
## stringToFiles
### Description
Converts a string representation of files and directories to real files and directories in the file system.
### Method
`POST` (or `PUT`, depending on API design conventions for data manipulation)
### Endpoint
`/kshutkin/package-build/api/stringToFiles` (Example endpoint, actual endpoint may vary)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **data** (string) - Required - A string representing the desired file and directory structure.
- **baseDir** (string) - Required - The base directory where the files and directories should be created.
### Request Example
```json
{
"data": "file1.txt:Hello\ndir1/file2.txt:World",
"baseDir": "/tmp/test"
}
```
### Response
#### Success Response (200)
- **message** (string) - Indicates successful conversion. (e.g., "Filesystem updated successfully.")
#### Response Example
```json
{
"message": "Filesystem updated successfully."
}
```
```
--------------------------------
### Set output directory to 'dist'
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This CLI option specifies the destination directory for the build output. If not provided, pkgbld defaults to a standard output location.
```bash
pkgbld --dest=dist
```
--------------------------------
### Prune devDependencies and redundant scripts
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
The 'prune' command cleans up your package.json by removing development dependencies and unnecessary scripts. This helps in creating a leaner production build.
```bash
pkgbld prune
```
--------------------------------
### Compress ES and UMD formats
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command enables compression using terser for the specified formats (e.g., 'es', 'umd'). By default, only UMD bundles are compressed.
```bash
pkgbld --compress=es,umd
```
--------------------------------
### Generated package.json for Library
Source: https://context7.com/kshutkin/package-build/llms.txt
The 'package.json' file generated after initializing the project with pkgbld. It includes metadata, build scripts, dependencies, and configuration for module formats (ES, CJS) and output directories.
```json
{
"name": "my-awesome-lib",
"version": "1.0.0",
"description": "An awesome library for awesome things",
"license": "MIT",
"author": "John Doe ",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"files": ["dist"],
"scripts": {
"build": "pkgbld --formats=es,cjs",
"prepack": "pkgbld prune"
},
"repository": {
"type": "git",
"url": "git+https://github.com/johndoe/my-awesome-lib.git"
},
"bugs": {
"url": "https://github.com/johndoe/my-awesome-lib/issues"
},
"homepage": "https://github.com/johndoe/my-awesome-lib#readme",
"devDependencies": {
"pkgbld": "^1.0.0",
"typescript": "^5.0.0"
}
}
```
--------------------------------
### Plugin Behavior for TypeScript Declaration Bundling (TypeScript)
Source: https://context7.com/kshutkin/package-build/llms.txt
This TypeScript comment outlines the automatic behaviors of the 'pkgbld-plugin-dts-buddy'. It explains that the plugin sets 'noSubpackages = true', bundles all '.d.ts' files, maintains type import/export structure, and is compatible with the 'package.json' exports field, simplifying the TypeScript build process.
```typescript
// Plugin automatically:
// 1. Sets noSubpackages = true (no subpackage directories created)
// 2. Bundles all .d.ts files into single output
// 3. Maintains type imports/exports structure
// 4. Works with package.json exports field
```
--------------------------------
### Core Package package.json Build Script
Source: https://context7.com/kshutkin/package-build/llms.txt
package.json for the '@workspace/core' package. Its 'build' script uses 'pkgbld-internal' to compile the package into ES and CommonJS formats.
```json
{
"name": "@workspace/core",
"version": "1.0.0",
"scripts": {
"build": "pkgbld-internal --formats=es,cjs",
"clean": "xc6 rm dist"
},
"dependencies": {
"@workspace/utils": "workspace:*"
}
}
```
--------------------------------
### Use pkgbld Prune for Pre-publish Cleanup
Source: https://context7.com/kshutkin/package-build/llms.txt
Explains how to use the `pkgbld prune` command to clean up a project's package.json and file structure before publishing to npm. This includes removing development dependencies, dev scripts, and optionally flattening the output directory or removing source maps.
```bash
# Basic prune - removes devDependencies and dev scripts
npx pkgbld prune
# Flatten dist directory to root (moves dist/* to ./
npx pkgbld prune --flatten
# Remove source maps from package
npx pkgbld prune --remove-sourcemaps
# Combined cleanup before publishing
npx pkgbld prune --flatten --remove-sourcemaps --optimize-files
```
--------------------------------
### Rollup Configuration for Package Builds (JavaScript)
Source: https://context7.com/kshutkin/package-build/llms.txt
This JavaScript configuration file sets up Rollup for building packages. It defines input and output formats (ES, CJS, UMD), integrates TypeScript compilation, node module resolution, commonJS module handling, and Terser for minification. It also specifies external dependencies and sourcemap generation.
```javascript
import typescript from '@rollup/plugin-typescript';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import terser from '@rollup/plugin-terser';
export default [
{
input: 'src/index.ts',
output: [
{ file: 'dist/index.mjs', format: 'es', sourcemap: false },
{ file: 'dist/index.cjs', format: 'cjs', sourcemap: false },
{
file: 'dist/index.umd.js',
format: 'umd',
name: 'MyLibrary',
sourcemap: true,
plugins: [terser()]
}
],
plugins: [
typescript({ declaration: true, declarationDir: 'dist' }),
nodeResolve(),
commonjs()
],
external: ['lodash', 'react']
}
];
```
--------------------------------
### Generate source maps for ES and CJS targets
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option generates source maps for the specified build targets ('es', 'cjs'). Source maps help in debugging by mapping compiled code back to the original source. The default target for source maps is 'umd'.
```bash
pkgbld --sourcemaps=es,cjs
```
--------------------------------
### Root pnpm-workspace.yaml Configuration
Source: https://context7.com/kshutkin/package-build/llms.txt
Configuration file for pnpm workspaces, specifying which directories should be included as packages within the monorepo. It points to all subdirectories within the 'packages' folder.
```yaml
packages:
- 'packages/*'
```
--------------------------------
### Bundle specific external dependencies
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option allows you to specify which external dependencies (e.g., 'lodash') should be bundled with your package. This provides more control over the final bundle.
```bash
pkgbld --include-externals=lodash
```
--------------------------------
### Generate Multiple UMD Builds with pkgbld CLI
Source: https://context7.com/kshutkin/package-build/llms.txt
This command uses pkgbld to create ES, CommonJS, and UMD module formats. It specifically configures two UMD builds with custom global variable names: 'index' mapped to 'MyLibrary' and 'react-components' mapped to 'MyLibraryReact'.
```bash
npx pkgbld --formats=es,cjs,umd --umd=index,react-components
```
--------------------------------
### Plugin Package.json Configuration (JSON)
Source: https://context7.com/kshutkin/package-build/llms.txt
This JSON file defines the metadata for a pkgbld plugin package. It specifies the package name, version, module type ('module' for ES modules), main entry point, exports, and peer dependencies, ensuring compatibility with the pkgbld system.
```json
{
"name": "pkgbld-plugin-my-plugin",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.mjs",
"exports": {
".": "./dist/index.mjs"
},
"peerDependencies": {
"pkgbld": ">=1.0.0"
}
}
```
--------------------------------
### Configure UMD Builds in package.json
Source: https://context7.com/kshutkin/package-build/llms.txt
This JSON configuration within package.json defines the library's name and maps specific entry points to custom global variable names for UMD builds. It also specifies the 'exports' field, pointing to the source files for different module types.
```json
{
"name": "my-library",
"umd": {
"index": "MyLibrary",
"react-components": "MyLibraryReact"
},
"exports": {
".": "./src/index.ts",
"./react-components": "./src/react-components.tsx"
}
}
```
--------------------------------
### Convert string to file system entries (TypeScript)
Source: https://github.com/kshutkin/package-build/blob/main/cli-test-helper/README.md
The `stringToFiles` function converts a string representation of files and directories into actual file system entries. It requires the data string and a base directory path. This is useful for setting up test environments.
```typescript
/**
* Converts a string to real files and directories in the file system.
*/
export function stringToFiles(data: string, baseDir: string): Promise;
```
--------------------------------
### Define UMD output pattern
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option customizes the filename pattern for UMD (Universal Module Definition) output files. The default pattern is '[name].umd.js'.
```bash
pkgbld --umd-pattern=[name].js
```
--------------------------------
### Bundle all external dependencies
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This flag tells pkgbld to bundle all external dependencies into the output package. This can increase the bundle size but ensures all dependencies are included.
```bash
pkgbld --include-externals
```
--------------------------------
### Custom pkgbld Plugin Development (TypeScript)
Source: https://context7.com/kshutkin/package-build/llms.txt
This TypeScript code defines a custom plugin for pkgbld, allowing developers to hook into various stages of the build process. It demonstrates how to modify CLI options, process `package.json` and `tsconfig.json`, provide custom Rollup plugins, adjust output settings, and execute post-build tasks. It leverages the `PkgbldPlugin` interface and Rollup's plugin API.
```typescript
// my-plugin/src/index.ts
import type { PkgbldPlugin, CliOptions, ParsedOptions, PackageJson } from 'pkgbld';
import type { OutputOptions, Plugin } from 'rollup';
export function create(): Partial {
let buildDir: string;
let customConfig = { minify: true };
return {
// 1. Modify CLI options after parsing
options(parsedArgs: ParsedOptions, options: CliOptions) {
if (options.kind === 'build') {
buildDir = options.dir;
// Force specific formats
if (parsedArgs['--my-flag']) {
options.formats = ['es'];
}
}
},
// 2. Modify package.json during build
processPackageJson(packageJson: PackageJson, inputs: string[]) {
packageJson.keywords = [...(packageJson.keywords || []), 'built-with-pkgbld'];
packageJson.sideEffects = false;
},
// 3. Modify tsconfig.json
processTsConfig(config: any) {
config.compilerOptions = config.compilerOptions || {};
config.compilerOptions.strict = true;
config.compilerOptions.target = 'ES2020';
},
// 4. Provide custom Rollup plugins
async providePlugins(provider, config, inputs, inputsExt) {
// Import and register a custom Rollup plugin
const replace = await provider.import('@rollup/plugin-replace', 'default');
provider.provide(
() => replace({
'process.env.NODE_ENV': JSON.stringify('production'),
preventAssignment: true
}),
45 // Priority (0-100, higher runs later)
);
// Add different plugins per format
if (customConfig.minify) {
const terser = await provider.import('@rollup/plugin-terser', 'default');
provider.provide(
() => terser({ compress: { drop_console: true } }),
90,
{ format: ['es', 'cjs'] } // Only for ES and CJS
);
}
},
// 5. Modify output settings per format
getExtraOutputSettings(format, inputs) {
if (format === 'umd') {
return {
globals: {
react: 'React',
'react-dom': 'ReactDOM'
}
};
}
return {};
},
// 6. Post-build hook
async buildEnd() {
console.log('Build completed! Running post-build tasks...');
// Generate documentation, upload to CDN, etc.
await generateDocs(buildDir);
}
};
}
async function generateDocs(dir: string) {
// Custom documentation generation logic
}
```
--------------------------------
### Define CommonJS output pattern
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option customizes the filename pattern for CommonJS output files. The default pattern is '[name].cjs'.
```bash
pkgbld --commonjs-pattern=[name].js
```
--------------------------------
### Bundle Specific External Dependencies
Source: https://context7.com/kshutkin/package-build/llms.txt
Command to instruct pkgbld to bundle specific external dependencies (e.g., lodash, date-fns) into the output, rather than treating them as external imports. Useful for reducing external requests or ensuring specific versions.
```bash
npx pkgbld --include-externals=lodash,date-fns
```
--------------------------------
### Eject Rollup configuration
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command allows you to extract the underlying Rollup configuration file. This is useful for advanced customization that goes beyond pkgbld's CLI options.
```bash
pkgbld --eject
```
--------------------------------
### Filesystem to String Conversion
Source: https://github.com/kshutkin/package-build/blob/main/cli-test-helper/README.md
Converts the content of files and directories within a specified base directory into a single string representation.
```APIDOC
## filesToString
### Description
Converts files and directories in the file system to a string representation.
### Method
`GET` (or `POST` with an empty body if preferred for data retrieval)
### Endpoint
`/kshutkin/package-build/api/filesToString` (Example endpoint, actual endpoint may vary)
### Parameters
#### Path Parameters
None
#### Query Parameters
- **baseDir** (string) - Required - The base directory from which to read files and directories.
#### Request Body
None (if using GET)
### Request Example
(No request body for GET method)
### Response
#### Success Response (200)
- **content** (string) - A string representing the combined content of the files and directories.
#### Response Example
```json
{
"content": "file1.txt:Hello\ndir1/file2.txt:World"
}
```
```
--------------------------------
### pkgbld Build Tool: Automatically Updated package.json
Source: https://context7.com/kshutkin/package-build/llms.txt
Illustrates the automatic updates made to a project's package.json file by the pkgbld build tool after a successful build. This includes setting main, module, unpkg, types, and exports fields to point to the generated build artifacts.
```json
{
"name": "my-library",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"unpkg": "./dist/index.umd.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./utils": {
"types": "./dist/utils.d.ts",
"import": "./dist/utils.mjs",
"require": "./dist/utils.cjs"
},
"./react": {
"types": "./dist/react.d.ts",
"import": "./dist/react.mjs",
"require": "./dist/react.cjs"
}
},
"files": ["dist"]
}
```
--------------------------------
### Remove source map files and references
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command removes all files with the '.map' extension and also removes source map reference comments (e.g., '//# sourceMappingURL=') from the code. This is useful for cleaning up production builds.
```bash
pkgbld prune --remove-sourcemaps
```
--------------------------------
### PkgbldPlugin Interface Definition for TypeScript
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
Defines the interface for package-build plugins. Plugins can implement methods like options, processPackageJson, processTsConfig, providePlugins, getExtraOutputSettings, and buildEnd to hook into the build process.
```typescript
interface PkgbldPlugin {
options(
parsedArgs: { [key: string]: string | number },
options: ReturnType
): void;
processPackageJson(
packageJson: PackageJson,
inputs: string[],
logger: Logger
): void;
processTsConfig(config: Json): void;
providePlugins(
provider: Provider,
config: Record,
inputs: string[]
): Promise;
getExtraOutputSettings(
format: InternalModuleFormat,
inputs: string[]
): Partial;
buildEnd(): Promise;
}
```
--------------------------------
### Convert file system entries to string (TypeScript)
Source: https://github.com/kshutkin/package-build/blob/main/cli-test-helper/README.md
The `filesToString` function converts files and directories from the file system into a string representation. It takes a base directory path as input and returns a Promise resolving to the string. This is useful for capturing the state of the file system after an operation.
```typescript
/**
* Converts files and directories in the file system to a string.
*/
export function filesToString(baseDir: string): Promise;
```
--------------------------------
### Eject Rollup Configuration with pkgbld --eject
Source: https://context7.com/kshutkin/package-build/llms.txt
Demonstrates how to use the `pkgbld --eject` command to generate a standalone `rollup.config.mjs` file. This allows for more advanced customization of the Rollup build process beyond the standard pkgbld configurations.
```bash
# Eject configuration
npx pkgbld --eject
```
--------------------------------
### Define ESM output pattern
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option customizes the filename pattern for ECMAScript Module (ESM) output files. The default pattern is '[name].mjs'.
```bash
pkgbld --esm-pattern=[name].js
```
--------------------------------
### Flatten directory structure
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This command flattens the file structure by moving all files from a specified directory (e.g., 'dist') to the root and updating package.json accordingly. If the directory is not specified, it's inferred from package.json. This command will fail if file name conflicts occur.
```bash
pkgbld prune --flatten=dist
```
--------------------------------
### Resulting Behavior of Bundled Externals
Source: https://context7.com/kshutkin/package-build/llms.txt
Illustrates the JavaScript output ('dist/index.mjs') where 'lodash' and 'date-fns' are bundled inline. Dependencies like 'react' remain external imports.
```javascript
// dist/index.mjs - lodash and date-fns bundled inline
import { useState } from 'react'; // react remains external
// Bundled lodash code inline
const cloneDeep = (obj) => { /* lodash code */ };
const debounce = (func, wait) => { /* lodash code */ };
// Bundled date-fns code inline
const format = (date, pattern) => { /* date-fns code */ };
export function MyComponent() {
const [state] = useState(cloneDeep({ date: format(new Date(), 'yyyy-MM-dd') }));
return state;
}
```
--------------------------------
### Disable Subpackage Directory Creation with package-build CLI
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
Prevents the creation of subpackage directories with package.json files for non-index entry points. This is useful for simplifying imports when not using alternative type resolution methods. The pkgbld-plugin-dts-buddy plugin automatically enables this.
```bash
pkgbld --no-subpackages
```
--------------------------------
### Prune and Optimize Files using package-build CLI
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
Disables file optimization during the package build process. This option is useful in edge cases where all files are required. It is part of the 'prune' command.
```bash
pkgbld prune --optimize-files=false
```
--------------------------------
### Disable TypeScript configuration check/write
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This flag prevents pkgbld from checking for or writing to the 'tsconfig.json' file. Use this if you manage your TypeScript configuration separately or don't need pkgbld's assistance with it.
```bash
pkgbld --no-ts-config
```
--------------------------------
### tsconfig.json for TypeScript Compilation
Source: https://context7.com/kshutkin/package-build/llms.txt
The 'tsconfig.json' file used for configuring the TypeScript compiler. It specifies compilation options such as target, module system, output directory, root directory, and declaration file generation, ensuring proper compilation for the project's TypeScript code.
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"declaration": true,
"declarationMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
},
"include": ["src"]
}
```
--------------------------------
### Remove Legal Comments during package-build Prune
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
Removes all legal comments from the package. This functionality is only active when the 'compress' option is also used. It is applied via the 'prune' command.
```bash
pkgbld prune --remove-legal-comments --compress=es,cjs
```
--------------------------------
### Prevent package.json update
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option disables pkgbld's automatic updates to the package.json file during the build process. Use this if you prefer to manage package.json manually.
```bash
pkgbld --no-update-package-json
```
--------------------------------
### Disable 'exports' field in package.json
Source: https://github.com/kshutkin/package-build/blob/main/pkgbld/README.md
This option prevents pkgbld from adding or modifying the 'exports' field in your package.json. The 'exports' field is crucial for defining package entry points and conditional exports.
```bash
pkgbld --no-exports
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.