### CLI Usage for Prepare Function Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Examples of how to use the `bunchee prepare` command for different package configurations and directories. ```bash # Standard package (CommonJS + ESM) bunchee prepare # ESM-only package bunchee prepare --esm # Specific directory bunchee prepare --cwd ./packages/my-lib ``` -------------------------------- ### Install bunchee Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Install bunchee as a development dependency using npm. ```bash npm install --save-dev bunchee ``` -------------------------------- ### Directory Structure Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-entries.md Illustrates the conventional directory structure for defining entry points and shared modules in Bunchee. ```tree src/ ├── index.ts # Entry for '.' ├── lite.ts # Entry for './lite' ├── index.development.ts # Entry for './index' with 'development' condition ├── index.production.ts # Entry for './index' with 'production' condition ├── index.react-server.ts # Entry for './index' with 'react-server' condition ├── react/ │ └── index.ts # Entry for './react' ├── features/ │ ├── foo.ts # Entry for './features/foo' │ └── bar.ts # Entry for './features/bar' ├── _util.ts # Shared module (not an entry point) ├── _helpers.ts # Shared module └── __tests__/ └── index.test.ts # Ignored (test file) ``` -------------------------------- ### Install Bunchee Source: https://github.com/huozhi/bunchee/blob/main/README.md Install bunchee and typescript as development dependencies. ```sh npm install --save-dev bunchee typescript ``` -------------------------------- ### Runtime-Specific Overrides Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-entries.md Shows how to structure source files for different runtimes and configure package.json 'exports' accordingly. ```tree src/ ├── index.ts # Default entry ├── index.react-server.ts # React Server Component version └── index.edge-light.ts # Edge runtime version ``` -------------------------------- ### Build Script Examples Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md Demonstrates various build script configurations using Bunchee CLI options for watch mode, minification, development builds with post-build commands, and specific format/target outputs. ```json { "scripts": { "build": "bunchee", "build:watch": "bunchee --watch", "build:prod": "bunchee --minify", "build:dev": "bunchee --watch --success 'npm run test'", "build:esm": "bunchee --format esm --target es2020", "build:cjs": "bunchee --format cjs --target es2015", "build:no-external": "bunchee --no-external" } } ``` -------------------------------- ### Example: Generated package.json After Prepare Command Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md This JSON shows the structure of a package.json file after running `bunchee prepare` with a specific src/ directory structure. ```json { "name": "mylib", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": ["dist"], "exports": { ".": { "import": { "types": "./dist/es/index.d.ts", "default": "./dist/es/index.js" }, "require": { "types": "./dist/cjs/index.d.cts", "default": "./dist/cjs/index.cjs" } }, "./lite": { "import": { "types": "./dist/es/lite.d.ts", "default": "./dist/es/lite.js" }, "require": { "types": "./dist/cjs/lite.d.cts", "default": "./dist/cjs/lite.cjs" } }, "./react": { "import": { "types": "./dist/es/react/index.d.ts", "default": "./dist/es/react/index.js" }, "require": { "types": "./dist/cjs/react/index.d.cts", "default": "./dist/cjs/react/index.cjs" } } } } ``` -------------------------------- ### Bunchee Lint Warnings Output Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Example output showing warnings generated during linting, highlighting issues like missing source files or exports not covered by the 'files' field. ```text ! The following exports are defined in package.json but missing source files: ⨯ ./missing ! "./lite" export missing from files field ! Type file ./dist/index.d.ts not marked with "types" condition ``` -------------------------------- ### Configure TypeScript Paths for Alias Plugin Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md Example tsconfig.json demonstrating how to set up path aliases for the Alias plugin. ```json { "compilerOptions": { "paths": { "@/*": ["src/*"], "@utils": ["src/utils.ts"] } } } ``` -------------------------------- ### Complex Exports Configuration Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-exports.md A comprehensive example of a package.json 'exports' field configuration, including standard, lite, react, and wildcard exports. ```json { "type": "module", "main": "./dist/index.js", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./lite": { "types": "./dist/lite.d.ts", "import": "./dist/lite.js", "require": "./dist/lite.cjs" }, "./react": { "types": "./dist/react.d.ts", "react-server": "./dist/react.server.js", "default": "./dist/react.js" }, "./features/*": "./dist/features/*.js" } } ``` -------------------------------- ### BrowserslistConfig Examples Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/types.md Illustrates the different formats for specifying browser compatibility using BrowserslistConfig: as a string, an array of strings, or an object for environment-specific configurations. ```typescript "last 2 versions" ``` ```typescript ["last 1 version", "> 1%", "not dead"] ``` ```typescript { "production": ["> 1%", "last 2 versions"], "development": ["last 1 chrome version"] } ``` -------------------------------- ### Content of a Text File Source: https://github.com/huozhi/bunchee/blob/main/README.md Example of a text file that will be imported as a string. ```txt hello world ``` -------------------------------- ### Consumer Usage Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Demonstrates how to import and use the Button component and the useClickOutside hook from the library in a consumer application. ```typescript // In consumer code import { Button } from '@myorg/ui-components' import { useClickOutside } from '@myorg/ui-components/hooks' export function App() { const outsideRef = useClickOutside(() => console.log('Clicked outside')) return (
) } ``` -------------------------------- ### Install Cross-Platform Script Runner Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Install `cross-env` to manage environment variables across different operating systems for build scripts. ```bash # Use cross-platform scripts npm install --save-dev cross-env ``` -------------------------------- ### Configure Executable CLI Build Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md Example configuration for making generated CLI scripts executable. It includes the 'bin' field for the entry point and a 'build' script that runs Bunchee and then uses 'chmod +x' to set execute permissions. ```json { "bin": "./dist/cli.js", "scripts": { "build": "bunchee && chmod +x ./dist/cli.js" } } ``` -------------------------------- ### Bunchee Lint Success Output Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Example of a successful linting operation, indicating that all checks passed. ```text ✓ Linting package.json... passed - Exports: 3 entries verified - Files field: all outputs covered - Type declarations: correctly configured ``` -------------------------------- ### Example Input Exports for Package.json Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/build-process.md Illustrates the structure of the `exports` field in `package.json` that the function processes. ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" }, "./lite": "./dist/lite.js" } ``` -------------------------------- ### Bunchee Lint Errors Output Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Example output indicating errors found during linting, such as missing export source files or extension mismatches. ```text ⨯ Linting failed: Export "./missing" declared but src/missing.ts not found ⨯ Extension mismatch: package.json type is "module" but export uses .cjs ``` -------------------------------- ### Inline CSS Plugin Input Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md Example of a TypeScript file importing a CSS file, which the Inline CSS plugin will process. ```typescript // src/index.ts import './styles.css' export const App = () =>
Hello
``` -------------------------------- ### Wildcard Export Patterns Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-exports.md Illustrates the use of wildcard patterns in the 'exports' field for automatic file discovery and mapping. ```json { "exports": { ".": "./dist/index.js", "./features/*": "./dist/features/*.js" } } ``` -------------------------------- ### Example Package Exports JSON Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/build-process.md Illustrates the structure of the 'exports' field in package.json, including nested conditions and shorthand notations. ```json { "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" }, "./lite": "./dist/lite.js" } } ``` -------------------------------- ### GitHub Actions CI/CD Workflow Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Example GitHub Actions workflow for building, linting, testing, and deploying your project. Ensure Node.js is set up and dependencies are cached. ```yaml name: Build and Test on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' cache: 'npm' - run: npm ci - run: npm run build - run: npm run lint - run: npm test - run: npm run build:prod ``` -------------------------------- ### Composed Export Types Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-exports.md Demonstrates how to define composed export types in package.json for different build environments. ```typescript // Example in exports: './lite': { 'development': './dist/lite.development.js', 'production': './dist/lite.production.js', 'default': './dist/lite.js' } // This creates tuples with composed types: // [['dist/lite.development.js', 'development']] // [['dist/lite.production.js', 'production']] ``` -------------------------------- ### Inline CSS Plugin Output Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md Illustrates the JavaScript output after the Inline CSS plugin inlines the CSS. ```javascript const style = document.createElement('style') style.textContent = '...minified css...' document.head.appendChild(style) export const App = () => ... ``` -------------------------------- ### Example Result of Entry Collection Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/build-process.md Shows the expected output format after mapping input exports to discovered source files. ```typescript { './index': { source: '/project/src/index.ts', name: '.', export: { types: 'dist/index.d.ts', import: 'dist/index.mjs', require: 'dist/index.cjs' } }, './lite': { source: '/project/src/lite.ts', name: './lite', export: { default: 'dist/lite.js' } } } ``` -------------------------------- ### Shared Modules Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-entries.md Demonstrates how files prefixed with an underscore are treated as shared modules, bundled once, and reused across multiple entry points. ```typescript // src/_util.ts export function helper() { /* ... */ } // src/index.ts import { helper } from './_util' export const foo = () => helper() // src/lite.ts import { helper } from './_util' export const bar = () => helper() ``` -------------------------------- ### Migrate to Bunchee from Other Bundlers Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Follow these steps to migrate your project to Bunchee. This includes installation, auto-configuration, updating build scripts, and committing changes. ```bash # 1. Install bunchee npm install --save-dev bunchee # 2. Auto-configure bunchee prepare # 3. Update build script npm pkg set scripts.build="bunchee" # 4. Build and test npm run build npm test # 5. Commit changes git add -A git commit -m "chore: migrate to bunchee" ``` -------------------------------- ### Example Entries Object Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-entries.md Illustrates the structure of the Entries object, showing how export paths map to their corresponding source file details and export conditions. ```typescript // Example: { './index': { source: '/project/src/index.ts', name: '.', export: { default: 'dist/index.js', types: 'dist/index.d.ts' } }, './lite': { source: '/project/src/lite.ts', name: './lite', export: { default: 'dist/lite.js' } } } ``` -------------------------------- ### Example Usage of collectSourceEntries Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Demonstrates how to call the `collectSourceEntries` function and shows the expected structure of its return value, including binary entries and export path mappings. ```typescript const result = await collectSourceEntries( '/project/src', parsedExports, pkg ) // result.bins = new Set(['cli', 'server']) // result.exportsEntries = Map { // './index' => Set(['index.ts']), // './lite' => Set(['lite.ts', 'lite.tsx']), // './react' => Set(['react/index.ts']) // } ``` -------------------------------- ### Build with Sourcemaps Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Build your project with sourcemaps enabled for easier debugging. This snippet also shows how to check the installed version of Rollup. ```bash # Build with sourcemaps bunchee --sourcemap ``` ```bash # Inspect bundle composition npm install --save-dev rollup npx rollup --version ``` -------------------------------- ### Initialize a New Library Project Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Use npm to create a new directory, initialize a package.json, and navigate into the project. ```bash mkdir my-lib cd my-lib npm init -y ``` -------------------------------- ### Initialize Project and Run Bunchee Prepare Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Sets up a new project with a basic package.json and source files, then uses `bunchee prepare` to auto-configure the exports field, followed by `npm run build`. ```bash # Create initial package.json cat > package.json << EOF { "name": "@myorg/mylib", "version": "0.0.1", "description": "My library" } EOF # Create src files mkdir src echo "export const helper = () => {}" > src/index.ts echo "export const lite = () => {}" > src/lite.ts # Auto-configure bunchee prepare # Result: package.json updated with exports field npm run build # Output: dist/ folder generated with compiled files ``` -------------------------------- ### Create Entry Files and Package.json Source: https://github.com/huozhi/bunchee/blob/main/README.md Set up the directory structure and create initial files for a new package. ```sh cd ./coffee mkdir src && touch ./src/index.ts && touch package.json ``` -------------------------------- ### Setting up Binary CLI Entry Points in Bunchee Source: https://github.com/huozhi/bunchee/blob/main/README.md Structure your project with a 'src/bin/' directory to match 'bin' field entries in package.json for building executable files. ```bash |- src/ |- bin/ |- index.ts ``` -------------------------------- ### Bunchee Build with Multiple Options Combined Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Demonstrates combining various build options, including watch mode, minification, specific format and target, environment variable inlining, and a post-build success command. ```bash bunchee \ --watch \ --minify \ --format esm \ --target es2020 \ --runtime browser \ --env NODE_ENV,DEBUG \ --success "echo Build complete" ``` -------------------------------- ### FullExportCondition Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/types.md Shows the flattened version of an ExportCondition, where all conditions are at a single level. ```typescript // Input ExportCondition: { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" } // Result as FullExportCondition: { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" } ``` -------------------------------- ### Configure package.json for Basic Library Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Set up the package.json with main, types, files, exports, and build scripts for a basic library. ```json { "name": "@myorg/my-lib", "version": "1.0.0", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": ["dist"], "exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" } }, "scripts": { "build": "bunchee", "build:watch": "bunchee --watch", "prepare": "npm run build" } } ``` -------------------------------- ### Monorepo Build Order with pnpm Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Demonstrates how to build specific packages in a monorepo sequentially using pnpm filters to manage build order. ```bash # Build utils package first npm run build --filter @myorg/utils # Then packages that depend on it npm run build --filter @myorg/react ``` -------------------------------- ### Build and Verify Library Output Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Run the build script to generate the bundled JavaScript and type definition files in the dist directory. ```bash npm run build # Creates: # - dist/index.js (bundle) # - dist/index.d.ts (types) ``` -------------------------------- ### Test Basic Library Build Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Create a test JavaScript file to import and use the library's exported function, then run it with Node.js. ```bash cat > test.js << 'EOF' import { greet } from './dist/index.js' console.log(greet('World')) EOF node test.js # Output: Hello, World! ``` -------------------------------- ### Implement CLI Tool Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Create a CLI entry point file that imports and uses the library's main function. ```typescript // src/cli.ts #!/usr/bin/env node import { main } from './index.js' const args = process.argv.slice(2) main(args) ``` -------------------------------- ### Basic Bunchee Build Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Executes a basic build using default settings. Reads `package.json` exports and builds all entries from the `src/` directory. ```bash bunchee ``` -------------------------------- ### Prepare Package with Bunchee Source: https://github.com/huozhi/bunchee/blob/main/README.md Use Bunchee to prepare package.json configuration for publishing. ```sh # Use bunchee to prepare package.json configuration npm exec bunchee prepare # "If you're using other package manager such as pnpm" # pnpm bunchee prepare # "Or use with npx" # npx bunchee@latest prepare ``` -------------------------------- ### Run bunchee build Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Execute the build command defined in package.json. ```bash npm run build ``` -------------------------------- ### ParsedExportCondition Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/types.md Represents a parsed export entry including source file path, export name, and mapped conditions. ```typescript { source: '/project/src/index.ts', name: '.', export: { default: 'dist/index.js', types: 'dist/index.d.ts' } } ``` -------------------------------- ### Create TypeScript Source File Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Create a source directory and a basic TypeScript file for your library's entry point. ```bash mkdir src cat > src/index.ts << 'EOF' export function greet(name: string): string { return `Hello, ${name}!` } EOF ``` -------------------------------- ### Create and Use Output State Plugin Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md Demonstrates how to create an instance of the output state plugin and retrieve bundle size statistics. The result shows a Map where keys are paths and values are arrays of file statistics. ```typescript import { createOutputState } from 'bunchee/plugins/output-state-plugin' const outputState = createOutputState({ entries }) const stats = outputState.getSizeStats() // Result: Map { '.': [['dist/index.js', 'src/index.ts', 12500]], './lite': [['dist/lite.js', 'src/lite.ts', 5200]] } ``` -------------------------------- ### Extract Package Typings Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-exports.md Use this function to get the 'types' or 'typings' field from a package.json metadata object. It prioritizes the 'types' field. ```typescript import { getPackageTypings } from 'bunchee' const pkg = { types: 'dist/index.d.ts' } const typings = getPackageTypings(pkg) // 'dist/index.d.ts' ``` -------------------------------- ### Bunchee CLI Commands Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/README.md Bunchee can be executed directly from the command line for building, watching, and configuring. Use flags to specify options like minify, sourcemap, and target. The 'prepare' command can auto-configure, and 'lint' validates the project. ```bash # Build bunchee ``` ```bash # Watch mode bunchee --watch ``` ```bash # With options bunchee --minify --sourcemap --target es2020 ``` ```bash # Auto-configure bunchee prepare --esm ``` ```bash # Validate bunchee lint ``` -------------------------------- ### Build and Test Multi-Export Library Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Build the library and test its different exports (main, lite variant, CLI) using Node.js. ```bash npm run build # Test library node -e "import('./dist/index.js').then(m => console.log(m.greet('World')))" # Test lite variant node -e "import('./dist/lite.js').then(m => console.log(m.fastGreet()))" # Test CLI ./dist/cli.js --help ``` -------------------------------- ### `prepare` Function Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Auto-configures package.json with exports field and build settings. It scans the `src/` directory, discovers entry names, generates export conditions, and creates or updates the `package.json` file with appropriate fields like `exports`, `main`, `types`, `files`, and `type: "module"` if the `--esm` flag is used. ```APIDOC ## `prepare` Function ### Description Auto-configure package.json with exports field and build settings. ### Signature ```typescript async function prepare( cwd: string, options?: { esm?: boolean } ): Promise ``` ### Parameters #### Path Parameters - **cwd** (string) - Required - Directory containing package.json to update. #### Query Parameters - **options.esm** (boolean) - Optional - Configure as ESModule package (set type: "module"). Defaults to `false`. ### Behavior The prepare function scans the `src/` directory for entry point files, discovers entry names based on file structure, generates export conditions for each entry, and creates or updates `package.json` with `exports`, `main`, `types`, `files` fields, and `type: "module"` if `--esm` flag is used. ### CLI Usage ```bash # Standard package (CommonJS + ESM) bunchee prepare # ESM-only package bunchee prepare --esm # Specific directory bunchee prepare --cwd ./packages/my-lib ``` ### Example **Command**: ```bash bunchee prepare ``` **Generated package.json (example)**: ```json { "name": "mylib", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": ["dist"], "exports": { ".": { "import": { "types": "./dist/es/index.d.ts", "default": "./dist/es/index.js" }, "require": { "types": "./dist/cjs/index.d.cts", "default": "./dist/cjs/index.cjs" } }, "./lite": { "import": { "types": "./dist/es/lite.d.ts", "default": "./dist/es/lite.js" }, "require": { "types": "./dist/cjs/lite.d.cts", "default": "./dist/cjs/lite.cjs" } }, "./react": { "import": { "types": "./dist/es/react/index.d.ts", "default": "./dist/es/react/index.js" }, "require": { "types": "./dist/cjs/react/index.d.cts", "default": "./dist/cjs/react/index.cjs" } } } } ``` ``` -------------------------------- ### Parsed Exports Info Type Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-exports.md Illustrates the structure of the `ParsedExportsInfo` type, which maps export paths to arrays of output paths and their types. ```typescript type ParsedExportsInfo = Map // Example: Map { './index' => [['dist/index.js', 'default'], ['dist/index.d.ts', 'types']], './lite' => [['dist/lite.js', 'default']], './react' => [['dist/react.js', 'import'], ['dist/react.cjs', 'require']] } ``` -------------------------------- ### Build with Bunchee CLI Source: https://github.com/huozhi/bunchee/blob/main/README.md Build your project using the Bunchee CLI, specifying runtime, output file, and target. ```sh cd # Build based on the package.json configuration bunchee --runtime node -o ./dist/bundle.js bunchee -f esm -o --target es2022 ./dist/bundle.esm.js ``` ```sh # Specify the input source file bunchee ./src/foo.ts -o ./dist/foo.js ``` -------------------------------- ### Enable Verbose Debug Output Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Enable debug output for all Bunchee modules or specific ones to get more detailed logs during the build process. ```bash # Enable debug output DEBUG=* bunchee ``` ```bash # Specific module DEBUG=bunchee:* bunchee ``` -------------------------------- ### Get Package Metadata Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/build-process.md Reads and parses the package.json file from the current working directory. Returns all fields or an empty object if the file is missing. ```typescript async function getPackageMeta(cwd: string): Promise ``` -------------------------------- ### Configure Package.json for Bunchee Source: https://github.com/huozhi/bunchee/blob/main/README.md Define package name, type, main output, and build script in package.json. ```json5 { "name": "coffee", "type": "module", "main": "./dist/index.js", "scripts": { "build": "bunchee" } } ``` -------------------------------- ### Bunchee Build for a Single Entry File Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Bundles a specific entry file, overriding the `package.json` exports configuration. The output is directed to a specified path. ```bash bunchee ./src/special.ts --output ./dist/special.js ``` -------------------------------- ### Node Binary Support - Single Binary Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Configure bunchee to build a single executable CLI tool by specifying the 'bin' field in package.json and placing the entry file in src/bin/. ```json { "bin": "./dist/bin.js" } ``` -------------------------------- ### Bunchee Build with Custom Output and Format Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Specifies a custom output file path and sets the bundle format to CommonJS (cjs). ```bash bunchee --output ./dist/bundle.js --format cjs ``` -------------------------------- ### Generate CommonJS Shim for ESM Exports Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md This example shows how the ESM Shim plugin generates a CommonJS shim for an ESM-only export to ensure compatibility with CommonJS consumers. ```javascript export { foo } ``` ```javascript const { foo } = require('./index.mjs') module.exports = { foo } module.exports.__esModule = true ``` -------------------------------- ### Node Binary Support - Multiple Binaries Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Support multiple executable CLI tools by defining keys in the 'bin' field of package.json and creating corresponding files in the src/bin/ directory. ```json { "bin": { "foo": "./dist/bin/foo.js", "bar": "./dist/bin/bar.js" } } ``` -------------------------------- ### Collect Entries Usage Example Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-entries.md Demonstrates how to use `collectEntriesFromParsedExports` to gather entry points from a project's package.json exports. Ensure `parseExports` is called first to process the package.json. ```typescript import { collectEntriesFromParsedExports } from 'bunchee' import { parseExports } from 'bunchee' const pkg = { name: 'mylib', type: 'module', exports: { '.': './dist/index.js', './lite': './dist/lite.js' } } const parsed = await parseExports(pkg, '/path/to/project') const entries = await collectEntriesFromParsedExports( '/path/to/project', parsed, pkg, undefined ) // Result: // { // './index': { // source: '/path/to/project/src/index.ts', // name: '.', // export: { default: 'dist/index.js' } // }, // './lite': { // source: '/path/to/project/src/lite.ts', // name: './lite', // export: { default: 'dist/lite.js' } // } // } ``` -------------------------------- ### Using experimental lifecycle callbacks Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-main.md Utilize experimental callbacks to hook into the build lifecycle, such as on build start, end, or error. This allows for custom logging or actions during the bundling process. ```typescript await bundle('', { cwd: process.cwd(), _callbacks: { onBuildStart: (context) => { console.log(`Building ${Object.keys(context.entries).length} entries`) }, onBuildEnd: (jobs) => { console.log(`Completed ${jobs.length} asset builds`) }, onBuildError: (error) => { console.error('Build failed:', error.message) } } }) ``` -------------------------------- ### Runtime-Specific Code Configuration Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md Configure Bunchee to generate separate outputs for different runtimes like React Server Components, Edge, or React Native. Each runtime gets an optimized output. ```text src/ ├── index.ts # Default ├── index.react-server.ts # React Server Components ├── index.edge-light.ts # Edge runtime (Cloudflare, etc.) └── index.react-native.ts # React Native ``` ```json { "exports": { ".": { "react-server": "./dist/index.react-server.js", "edge-light": "./dist/index.edge-light.js", "react-native": "./dist/index.react-native.js", "default": "./dist/index.js" } } } ``` -------------------------------- ### Mapping Multiple Binaries in package.json Source: https://github.com/huozhi/bunchee/blob/main/README.md For multiple named executables, create corresponding files in 'src/bin/' that match the keys in the 'bin' field of package.json. ```json5 { "bin": { "foo": "./dist/bin/a.js", "bar": "./dist/bin/b.js", }, } ``` -------------------------------- ### Rollup Plugins Pipeline Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/build-process.md Illustrates the sequence of plugins used in the Rollup build pipeline. This pipeline handles various transformations and optimizations, starting from resolving input files to producing the final bundled output. ```text Input File ↓ 1. Node Resolve (@rollup/plugin-node-resolve) ↓ 2. CommonJS Support (@rollup/plugin-commonjs) ↓ 3. JSON Support (@rollup/plugin-json) ↓ 4. Alias Resolution (bunchee alias-plugin) ↓ 5. Path Substitution (@rollup/plugin-replace) ↓ 6. Raw Imports (bunchee raw-plugin) ↓ 7. CSS Inlining (bunchee inline-css-plugin) ↓ 8. Native Addons (bunchee native-addon-plugin) ↓ 9. SWC Transpilation (rollup-plugin-swc3) ↓ 10. Preserve Directives (bunchee preserve-directives) ↓ 11. Output State (bunchee output-state-plugin) ↓ Bundled Output ``` -------------------------------- ### Single Binary/CLI Entry Configuration Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md Configures a single command-line interface executable for the package. The 'bin' field points to the script that will be executed. ```json { "name": "mylib", "bin": "./dist/cli.js", "exports": { ".": "./dist/index.js" } } ``` -------------------------------- ### Bunchee Expands Wildcard Exports Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Bunchee automatically expands wildcard patterns defined in package.json 'exports' to match your source files. This example shows how './features/*' expands to individual exports for 'auth', 'user', and 'settings'. ```json { "exports": { "./features/auth": "./dist/features/auth.js", "./features/user": "./dist/features/user.js", "./features/settings": "./dist/features/settings.js" } } ``` -------------------------------- ### Analyze Bundle Output and Dependencies Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Check the sizes of your output files, inspect exported modules, and analyze your project's dependencies. ```bash # Check output sizes ls -lah dist/ ``` ```bash # Check what's exported node -e "import('./dist/index.js').then(m => console.log(Object.keys(m)))" ``` ```bash # Analyze dependencies npm ls ``` -------------------------------- ### createOutputState Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md Creates an output state tracker instance that collects file size information during bundling to report output statistics and display build results. ```APIDOC ## createOutputState(options) ### Description Create an output state tracker instance. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```typescript import { createOutputState } from 'bunchee/plugins/output-state-plugin' const outputState = createOutputState({ entries }) ``` ### Response #### Success Response (200) Returns an object with `plugin()` and `getSizeStats()` methods. #### Response Example ```json { "plugin": "Function", "getSizeStats": "Function" } ``` ``` -------------------------------- ### Bundle with defaults from package.json Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-main.md Use this snippet for basic bundling when your project is configured via package.json. It leverages default settings for format, target, and other options. ```typescript import { bundle } from 'bunchee' await bundle('', { cwd: '/path/to/project' }) ``` -------------------------------- ### Using Shared Modules Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md Files prefixed with an underscore are treated as shared modules. They are bundled once and can be referenced by multiple entry chunks, improving efficiency. ```text src/ ├── _util.ts # Shared ├── _helpers.ts # Shared ├── index.ts # Uses _util.ts └── lite.ts # Uses _util.ts ``` -------------------------------- ### Multiple Binary/CLI Entries Configuration Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md Configures multiple command-line interface executables for the package. The 'bin' field is an object mapping command names to their respective script paths. ```json { "name": "mylib", "bin": { "mylib": "./dist/bin/cli.js", "mylib-web": "./dist/bin/web.js" }, "exports": { ".": "./dist/index.js" } } ``` -------------------------------- ### Raw Plugin Usage for Importing Files as Strings Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md Demonstrates importing various file types (Markdown, JSON, HTML) as raw string content using the ?raw query parameter. ```typescript import readme from './README.md?raw' import config from './config.json?raw' import template from './template.html?raw' export { readme, config, template } ``` -------------------------------- ### Configure package.json for build Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Add the 'build' script to your package.json to run bunchee. Ensure 'type' is set to 'module' if using ESM. ```json { "name": "coffee", "type": "module", "main": "./dist/index.js", "scripts": { "build": "bunchee" } } ``` -------------------------------- ### Import Native Node.js Addon Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/plugins-and-utilities.md Demonstrates how to import a native Node.js .node binary file in your source code. The plugin ensures the .node file is copied to the output directory and the import path is rewritten correctly for runtime. ```typescript // src/index.ts import addon from './native.node' export function useAddon() { return addon.doSomething() } ``` ```typescript // dist/index.js import addon from './native.node' // Still references file at runtime export function useAddon() { ... } ``` -------------------------------- ### Migrate from Rollup to Bunchee Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Migrate from Rollup by copying your exports configuration to `package.json` and then running `bunchee prepare` to auto-generate necessary configurations. ```bash # Copy exports config from rollup input/output # to package.json exports field # Then: bunchee prepare # auto-generate if not present npm run build ``` -------------------------------- ### Lint Main Field Configuration Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Verifies that the 'main' field in package.json points to an existing file. Warnings are issued if the file is not found. ```json { "main": "./dist/index.js" // ✓ File exists } ``` -------------------------------- ### Bundle All Type Dependencies Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Use this flag to bundle all type dependencies into a single `.d.ts` file for standalone use. ```bash bunchee --dts-bundle ``` -------------------------------- ### Browserslist Configuration for Target Browsers Source: https://github.com/huozhi/bunchee/blob/main/README.md Configure target browsers using the `browserslist` field in `package.json`. Bunchee uses this to determine the output bundle's compatibility. ```json5 { "browserslist": [ "last 1 version", "> 1%", "maintained node versions", "not dead", ], } ``` -------------------------------- ### Bunchee Default Directory Structure Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Illustrates the default output directory structure after a Bunchee build, including main entry points, type definitions, and variants. ```text dist/ ├── index.js # Main entry ├── index.d.ts # Type definitions ├── index.cjs # CommonJS variant ├── index.d.cts # CommonJS types ├── lite.js # Secondary entry ├── lite.d.ts ├── react.js # React export ├── react.server.js # React Server Component └── features/ ├── foo.js └── bar.js ``` -------------------------------- ### Bunchee Build with Post-Build Command Execution Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Specifies a shell command to be executed in the system's shell after a successful build. This is often used in watch mode for automated testing or verification. ```bash bunchee --success "node ./dist/index.js" ``` -------------------------------- ### Bunchee Build with Minification and Source Maps Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Configures the build to minify the output code and generate source map files (`.map`) for debugging purposes. ```bash bunchee --minify --sourcemap ``` -------------------------------- ### Pre-publication Checklist Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md A sequence of commands to ensure code quality, verify build output, and test imports before publishing a package. ```bash # 1. Lint configuration bunchee lint # 2. Clean build rm -rf dist npm run build # 3. Verify output ls -la dist/ # 4. Size check du -sh dist/ # 5. Test imports node -e "import('./dist/index.js').then(m => console.log(Object.keys(m)))" # 6. Publish npm publish ``` -------------------------------- ### Programmatic API for Bundling Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/README.md Use the `bundle` function from 'bunchee' to programmatically create builds. Configure output format, minification, sourcemaps, and type declaration generation. An `onSuccess` callback can be provided for post-build actions. ```typescript import { bundle } from 'bunchee' await bundle(cliEntryPath, { cwd: process.cwd(), format: 'esm', minify: true, sourcemap: true, dts: { respectExternal: true }, onSuccess: () => console.log('Done') }) ``` -------------------------------- ### Import raw files with query parameter Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Import any file as raw text content by appending the '?raw' query parameter to the import path. This is useful for non-text assets like JSON or CSS. ```javascript import readme from './README.md?raw' // Markdown as string import config from './config.json?raw' // JSON as string (not parsed) import styles from './styles.css?raw' // CSS as string ``` -------------------------------- ### Bunchee Package.json Configuration Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/usage-patterns.md Configure your package.json to define multiple entry points for different runtimes using Bunchee. This allows for conditional exports based on the environment. ```json { "name": "isomorphic-lib", "type": "module", "peerDependencies": { "react": "^18.2.0" }, "exports": { ".": { "react-server": "./dist/index.react-server.js", "default": "./dist/index.js" } }, "files": ["dist"], "scripts": { "build": "bunchee" } } ``` -------------------------------- ### Standard package.json Configuration Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md A standard configuration including main entry, types, files, and multiple export conditions for import and require. ```json { "name": "mylib", "version": "1.0.0", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": ["dist"], "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./lite": { "types": "./dist/lite.d.ts", "import": "./dist/lite.js", "require": "./dist/lite.cjs" } }, "scripts": { "build": "bunchee" } } ``` -------------------------------- ### CLI: Development Build with Watch Mode Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md Use this command for development builds. It sets the NODE_ENV to 'development' and enables watch mode and sourcemaps for efficient iteration. ```bash # Development NODE_ENV=development bunchee --watch --sourcemap ``` -------------------------------- ### Minimal package.json Configuration Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md This is the most basic configuration for a library using Bunchee. It specifies the package name, module type, and the main export path. ```json { "name": "mylib", "type": "module", "exports": { ".": "./dist/index.js" }, "scripts": { "build": "bunchee" } } ``` -------------------------------- ### CLI: Production Build with Minification Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md This command is used for production builds. It sets NODE_ENV to 'production' and enables minification and sourcemaps for optimized output. ```bash # Production NODE_ENV=production bunchee --minify --sourcemap ``` -------------------------------- ### Bunchee Build for Modern Browsers with Minification Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Targets modern browser environments with ES2022 syntax and enables minification for optimized browser delivery. ```bash bunchee --target es2022 --minify --runtime browser ``` -------------------------------- ### Bundle with bunchee CLI Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Use the bunchee CLI to bundle a JavaScript or TypeScript entry file to a specified output path. ```bash bunchee src/index.js --output dist/bundle.js ``` -------------------------------- ### Prepare Package for CommonJS Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Run this command to prepare a CommonJS package. It generates hybrid CommonJS and ESM exports, ensuring compatibility. ```bash bunchee prepare ``` -------------------------------- ### Prepare Specific Directory Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/api-reference-cli.md Use this option to prepare a package located in a specific directory. This is useful when managing multiple packages within a monorepo. ```bash bunchee prepare --cwd ./packages/my-lib ``` -------------------------------- ### CLI: Inline Environment Variables (Multiple) Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/configuration.md Include multiple environment variables like NODE_ENV, DEBUG_MODE, and API_KEY in the build. This allows for more granular control over build-time configurations. ```bash # Include multiple variables bunchee --env NODE_ENV,DEBUG_MODE,API_KEY ``` -------------------------------- ### Import text files Source: https://github.com/huozhi/bunchee/blob/main/docs/public/llms.txt Import text files directly as string content using the .txt or .data file extensions. ```javascript import data from './content.txt' // Imports as string ``` -------------------------------- ### CLI Usage for Bunchee Lint Source: https://github.com/huozhi/bunchee/blob/main/_autodocs/prepare-and-lint.md Demonstrates how to use the bunchee lint command from the CLI to validate the current directory or a specific directory. ```bash # Lint current directory bunchee lint # Lint specific directory bunchee lint --cwd ./packages/my-lib ```