### Bunup Multiple Configurations for Environments/Formats
Source: https://bunup.dev/docs/guide/config-file
This example demonstrates how to export an array of configurations from `bunup.config.ts`. Each configuration requires a `name` property for identification. This is useful for building for multiple environments (e.g., Node.js, browser) or formats (e.g., ESM, IIFE) in a single run.
```typescript
export default defineConfig([
{
entry: "src/index.ts",
name: 'node',
format: 'esm',
target: 'node',
},
{
entry: "src/browser.ts",
name: 'browser',
format: ['esm', 'iife'],
target: 'browser',
outDir: 'dist/browser',
},
]);
```
--------------------------------
### Basic Bunup Configuration File Setup
Source: https://bunup.dev/docs/guide/config-file
This snippet shows the fundamental structure for creating a `bunup.config.ts` file. It imports the `defineConfig` utility and exports a configuration object. This is the simplest way to centralize build settings.
```typescript
import { defineConfig } from 'bunup';
export default defineConfig({
// ...your configuration options go here
});
```
--------------------------------
### Create New Project with Bunup CLI
Source: https://bunup.dev/docs/scaffold-with-bunup
Initializes a new project using the Bunup CLI. This command prompts the user with questions to configure the project, offering 'Minimal' and 'Full' setup variants. The 'Minimal' setup is for users who prefer to configure their own environment, while 'Full' provides a complete modern library setup.
```shell
bunx @bunup/cli@latest create
```
--------------------------------
### Basic Copy Plugin Configuration - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Demonstrates the basic setup for the Bunup copy plugin in a TypeScript configuration file. It copies specified files and directories to the build output.
```typescript
import { defineConfig } from 'bunup';
import { copy } from 'bunup/plugins';
export default defineConfig({
plugins: [copy(['README.md', 'assets/**/*'])],
});
```
--------------------------------
### Bunup Package Configuration with Path Resolution Example
Source: https://bunup.dev/docs/guide/workspaces
This example demonstrates path resolution in a Bunup package configuration. The 'root' is set to 'packages/core', and 'entry' and 'outDir' are defined relative to this root. 'entry: "src/index.ts"' resolves to 'packages/core/src/index.ts', and 'outDir: "dist"' specifies output to 'packages/core/dist/'.
```typescript
{
name: "core",
root: "packages/core",
config: {
entry: "src/index.ts", // resolves to packages/core/src/index.ts
outDir: "dist", // outputs to packages/core/dist/
},
}
```
--------------------------------
### Install Bunup as a Development Dependency
Source: https://bunup.dev/index
This command installs Bunup as a development dependency in your project using the 'bun add' command. This makes Bunup available for your build scripts.
```shell
bun add --dev bunup
```
--------------------------------
### Create a TypeScript Function with Bunup
Source: https://bunup.dev/index
Example of a simple TypeScript function 'greet' that takes a name and returns a greeting string. This code snippet demonstrates basic TypeScript syntax.
```typescript
export function greet(name: string): string {
return `Hello, ${name}`;
}
```
--------------------------------
### Install React Compiler Plugin for Bunup
Source: https://bunup.dev/docs/recipes/react
Install the React Compiler plugin as a development dependency using npm or yarn. This plugin is essential for enabling automatic optimization of React components during the build process.
```bash
bun add --dev @bunup/plugin-react-compiler
```
--------------------------------
### Importing Package Styles
Source: https://bunup.dev/docs/guide/css
Example of how a consumer of a package would import the exported CSS file and components. This allows for easy integration of styles.
```javascript
import 'your-package/styles.css';
import { Button } from 'your-package';
```
--------------------------------
### Enable tsgo Experimental Compiler for Faster Declaration Generation
Source: https://bunup.dev/docs/guide/typescript-declarations
This snippet shows how to enable TypeScript's experimental native compiler (tsgo) for faster declaration generation. It requires installing a development dependency and can be configured via CLI or a Bunup configuration file. tsgo only works when `inferTypes` is enabled.
```sh
bun add --dev @typescript/native-preview
```
```sh
bunup --dts.infer-types --dts.tsgo
```
```typescript
export default defineConfig({
dts: {
inferTypes: true,
tsgo: true,
},
});
```
--------------------------------
### Bunup Multiple Configurations with Different Entry Points and Formats
Source: https://bunup.dev/docs/guide/config-file
This configuration illustrates defining multiple, distinct build configurations for different purposes, such as a main module needing both ESM and CJS formats, a CLI entry point needing only ESM, and a browser bundle. Each configuration is named for clarity.
```typescript
export default defineConfig([
{
entry: "src/index.ts",
name: 'main',
format: ['esm', 'cjs'],
},
{
entry: "src/cli.ts",
name: 'cli',
format: ['esm'],
},
{
entry: "src/browser.ts",
name: 'browser',
format: ['esm', 'iife'],
outDir: 'dist/browser'
},
]);
```
--------------------------------
### Using Bunup Custom Plugins
Source: https://bunup.dev/docs/guide/plugins
Shows how to use Bunup-specific plugins that offer custom lifecycle hooks for the build process. These hooks allow for actions before or after the build. Ensure the `BunupPlugin` type is imported from 'bunup'.
```typescript
import { defineConfig, type BunupPlugin } from 'bunup';
const myBunupPlugin: BunupPlugin = {
name: 'my-bunup-plugin',
hooks: {
onBuildStart(options) {
// Called before build starts
},
onBuildDone(context) {
// Called after build completes
}
}
};
export default defineConfig({
entry: 'src/index.ts',
plugins: [myBunupPlugin],
});
```
--------------------------------
### Create a Bunup Plugin with Lifecycle Hooks (TypeScript)
Source: https://bunup.dev/docs/advanced/plugin-development
Defines a custom Bunup plugin named 'my-bunup-plugin' that utilizes the 'onBuildStart' and 'onBuildDone' hooks. It logs build options and modifies the banner on build start, and logs file information and package name on build completion. Requires 'bunup' package.
```typescript
import type { BunupPlugin } from "bunup";
export function myBunupPlugin(): BunupPlugin {
return {
name: "my-bunup-plugin",
hooks: {
onBuildStart: async (ctx) => {
console.log("Starting build with options:", ctx.options);
ctx.options.banner = "/* Built with my plugin */";
},
onBuildDone: async (ctx) => {
const { files, options, meta } = ctx;
console.log("Build completed with files:", files.length);
console.log("Package name:", meta.packageJson.data?.name);
for (const file of files) {
console.log(`Generated: ${file.pathRelativeToOutdir} (${file.kind})`);
}
}
}
};
}
```
--------------------------------
### Using Bunup Built-in Copy Plugin
Source: https://bunup.dev/docs/guide/plugins
Illustrates the usage of Bunup's built-in `copy` plugin to include specific files and directories in the build output. This is useful for assets or documentation that should be present in the final distribution.
```typescript
import { defineConfig } from 'bunup';
import { copy } from 'bunup/plugins';
export default defineConfig({
entry: 'src/index.ts',
plugins: [
copy(['README.md', 'assets/**/*']),
],
});
```
--------------------------------
### Basic Bunup Workspace with Multiple Packages
Source: https://bunup.dev/docs/guide/workspaces
This example shows a minimal Bunup workspace configuration with two packages, 'core' and 'utils'. The 'core' package has custom build formats specified, while 'utils' uses default settings. It highlights the use of `defineWorkspace` and package configuration objects.
```typescript
import { defineWorkspace } from "bunup";
export default defineWorkspace([
{
name: "core",
root: "packages/core",
config: {
// Bunup finds 'src/index.ts' by default
// Or specify exactly which files to build
// entry: ["src/index.ts", "src/plugins.ts"],
format: ["esm", "cjs"],
},
},
{
name: "utils",
root: "packages/utils",
// Uses default entry points
// Uses default format: esm
// Generates .d.ts declaration files
},
]);
```
--------------------------------
### Configure package.json for Publishing React Library
Source: https://bunup.dev/docs/recipes/react
Sets up the `package.json` file for publishing a React component library. It defines entry points, files to include, and peer dependencies for React and React DOM.
```json
{
"name": "my-component-library",
"version": "1.0.0",
"type": "module",
"files": [
"dist"
],
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"./styles.css": "./dist/index.css",
"./package.json": "./package.json"
},
"peerDependencies": {
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
}
}
```
--------------------------------
### Bunup Build Options with TypeScript
Source: https://bunup.dev/docs/advanced/programmatic-usage
Illustrates how to configure the `build` function in TypeScript using `BuildOptions`. This example shows setting multiple output formats ('esm', 'cjs') for the build process. The `BuildOptions` type provides detailed control over the build, similar to `defineConfig`.
```typescript
import { build, type BuildOptions } from 'bunup';
const options: BuildOptions = {
entry: 'src/index.ts',
format: ['esm', 'cjs'],
};
await build(options);
```
--------------------------------
### Bunup Workspace with Multiple Build Configurations per Package
Source: https://bunup.dev/docs/guide/workspaces
This example demonstrates configuring multiple build outputs for a single package ('web') within a Bunup workspace. It uses an array for the 'config' property, requiring a 'name' for each build configuration to differentiate them in logs. Dependencies include the 'bunup' package.
```typescript
export default defineWorkspace([
{
name: "web",
root: "packages/web",
config: [
{
entry: "src/index.ts",
name: "node",
format: "esm",
target: "node",
},
{
entry: "src/browser.ts",
name: "browser",
format: ["esm", "iife"],
target: "browser",
outDir: "dist/browser",
},
],
},
]);
```
--------------------------------
### Install Bunup Tailwind CSS Plugin
Source: https://bunup.dev/docs/builtin-plugins/tailwindcss
Installs the official Bunup plugin for Tailwind CSS v4 using the bun package manager. This is the first step to integrating Tailwind CSS with Bunup.
```bash
bun add --dev @bunup/plugin-tailwindcss
```
--------------------------------
### Transform JSON Files - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Demonstrates transforming JSON files during the copy process using the `.transform()` method. This example minifies JSON content by re-parsing and stringifying it.
```typescript
// Simple transformation - minify JSON files
copy('data/**/*.json')
.transform(({ content }) => {
// Return content only - keeps original filename
return JSON.stringify(JSON.parse(content.toString()))
})
```
--------------------------------
### Example Scoped CSS Output
Source: https://bunup.dev/docs/builtin-plugins/tailwindcss
Shows the compiled CSS output for a component using prefixed Tailwind classes. The output demonstrates how styles are scoped with the 'yuku:' prefix and converted to CSS variables.
```css
@layer theme {
:root,
:host {
--yuku-color-blue-500: oklch(62.3% 0.214 259.815);
--yuku-color-blue-600: oklch(54.6% 0.245 262.881);
--yuku-color-white: #fff;
--yuku-spacing: 0.25rem;
--yuku-radius-md: 0.375rem;
}
}
@layer base, components;
@layer utilities {
.yuku\:rounded-md {
border-radius: var(--yuku-radius-md);
}
.yuku\:bg-blue-500 {
background-color: var(--yuku-color-blue-500);
}
.yuku\:px-4 {
padding-inline: calc(var(--yuku-spacing) * 4);
}
.yuku\:py-2 {
padding-block: calc(var(--yuku-spacing) * 2);
}
.yuku\:text-white {
color: var(--yuku-color-white);
}
@media (hover: hover) {
.yuku\:hover\:bg-blue-600:hover {
background-color: var(--yuku-color-blue-600);
}
}
}
```
--------------------------------
### Specify Custom Bunup Configuration File Path (CLI)
Source: https://bunup.dev/docs/guide/config-file
This demonstrates how to use the `--config` (or `-c`) CLI option to point Bunup to a configuration file located at a non-standard path or with a custom name. This provides flexibility in organizing configuration files.
```bash
bunup --config ./configs/custom.bunup.config.ts
# or using alias
bunup -c ./configs/custom.bunup.config.ts
```
--------------------------------
### Import and Use Published React Component Library
Source: https://bunup.dev/docs/recipes/react
Demonstrates how a consumer would import and use the published React component library. It includes importing the library's CSS and the Button component.
```tsx
import 'my-component-library/styles.css'
import { Button } from 'my-component-library'
function App() {
return
}
```
--------------------------------
### Bundle Size Reporter Plugin (TypeScript)
Source: https://bunup.dev/docs/advanced/plugin-development
This TypeScript plugin for Bunup analyzes built entry-point files, calculates their sizes in KB, and logs them. It can optionally throw an error if any bundle exceeds a predefined maximum size, aiding in performance optimization.
```typescript
export function bundleSizeReporter(maxSize?: number): BunupPlugin {
return {
name: "bundle-size-reporter",
hooks: {
onBuildDone: async ({ files }) => {
const sizes = await Promise.all(
files
.filter(f => f.kind === 'entry-point')
.map(async (file) => {
const buffer = await Bun.file(file.fullPath).arrayBuffer();
return {
path: file.pathRelativeToOutdir,
size: buffer.byteLength,
format: file.format
};
})
);
console.log("\nš¦ Bundle Sizes:");
for (const { path, size, format } of sizes) {
const sizeKB = (size / 1024).toFixed(2);
console.log(` ${path} (${format}): ${sizeKB} KB`);
if (maxSize && size > maxSize) {
throw new Error(`Bundle ${path} exceeds maximum size of ${maxSize} bytes`);
}
}
}
}
};
}
```
--------------------------------
### Component Import with Injected CSS
Source: https://bunup.dev/docs/builtin-plugins/tailwindcss
Demonstrates how consumers import components when the 'inject' option is enabled. The CSS is automatically loaded with the JavaScript, simplifying the consumer's setup.
```javascript
import { Button } from 'your-package';
;
```
--------------------------------
### Bunup Build with Plugins (TypeScript)
Source: https://bunup.dev/docs/advanced/programmatic-usage
Demonstrates using plugins programmatically with Bunup in TypeScript. This example integrates the `tailwindcss` plugin for CSS processing and the `copy` plugin for file copying. Plugins are configured within the `plugins` array of the build options.
```typescript
import { build } from 'bunup';
import { copy } from 'bunup/plugins';
import { tailwindcss } from '@bunup/plugin-tailwindcss';
await build({
entry: 'src/index.ts',
plugins: [
tailwindcss({
minify: true,
}),
copy(['README.md', 'assets/**/*']),
]
});
```
--------------------------------
### Configure Watch Mode in package.json
Source: https://bunup.dev/index
This JSON snippet demonstrates how to configure both a standard 'build' script and a 'dev' script for watch mode in your package.json. The 'dev' script allows you to start Bunup in watch mode with 'bun run dev'.
```json
{
"name": "my-package",
"scripts": {
"build": "bunup",
"dev": "bunup --watch"
}
}
```
--------------------------------
### Using Native Bun Plugins with Bunup
Source: https://bunup.dev/docs/guide/plugins
Demonstrates how to integrate native Bun plugins directly into your Bunup configuration. These plugins are passed to Bun's underlying bundler without modification. Ensure the `BunPlugin` type is imported from 'bun'.
```typescript
import { defineConfig } from 'bunup';
import type { BunPlugin } from 'bun';
const myBunPlugin: BunPlugin = {
name: 'my-plugin',
setup(build) {
// Bun plugin setup
}
};
export default defineConfig({
entry: 'src/index.ts',
plugins: [myBunPlugin],
});
```
--------------------------------
### CSS Modules for Scoped Styles
Source: https://bunup.dev/docs/guide/css
Example of using CSS Modules by appending '.module.css' to the filename. This scopes class names to prevent style conflicts. The imported 'styles' object maps local class names to unique generated class names.
```css
.primary {
background-color: #007bff;
color: white;
padding: 8px 16px;
border: none;
border-radius: 4px;
}
```
--------------------------------
### Filter Bunup Builds by Configuration Name (CLI)
Source: https://bunup.dev/docs/guide/config-file
These CLI commands show how to use the `--filter` option to build only specific configurations defined in your `bunup.config.ts` file. You can filter by a single configuration name or multiple names separated by commas. This is useful for testing individual builds.
```bash
# Single
bunup --filter main
# Multiple
bunup --filter main,browser
```
--------------------------------
### Use Prefixed Tailwind Classes in React Button
Source: https://bunup.dev/docs/recipes/react
Applies Tailwind CSS classes with a `mylib:` prefix to the Button component. This ensures that the styles are scoped and do not conflict with the consumer's Tailwind setup.
```tsx
export function Button(props: React.ComponentProps<'button'>): React.ReactNode {
return (
)
}
```
--------------------------------
### Bunup Development Workflow Commands
Source: https://bunup.dev/docs/scaffold-with-bunup
Provides essential commands for the development workflow in a Bunup-scaffolded project. These commands facilitate starting the development server, running tests, checking and fixing code style, type checking, and building the production bundle. The 'dev' command's behavior varies based on project type (React or TypeScript library).
```shell
bun run dev
bun run test
bun run lint
bun run lint:fix
bun run type-check
bun run build
```
--------------------------------
### Run Post-build Script with Simple Command in defineConfig
Source: https://bunup.dev/docs/guide/options
Configure a simple shell command to run after a successful build by setting the 'onSuccess' option to a string.
```typescript
export default defineConfig({
onSuccess: 'bun run ./scripts/server.ts',
});
```
--------------------------------
### Define onBuildStart Hook Signature (TypeScript)
Source: https://bunup.dev/docs/advanced/plugin-development
Defines the TypeScript signature for the 'onBuildStart' hook within a Bunup plugin. This hook is executed before the build process begins and receives a context object containing build options, which can be modified. Requires 'bunup' package.
```typescript
onBuildStart: (ctx: OnBuildStartCtx) => Promise | void
```
--------------------------------
### Define Multiple Entry Points with Bunup CLI (Method 1)
Source: https://bunup.dev/docs/guide/options
This CLI command specifies multiple entry point files for Bunup. Each file will be bundled into a separate output file.
```shell
bunup src/index.ts src/cli.ts
```
--------------------------------
### Initial NPM Publish for Bunup Projects
Source: https://bunup.dev/docs/scaffold-with-bunup
Commands for the initial publishing of packages to NPM. For monorepos, navigate to the specific package directory before publishing. For single-package projects, publish from the root directory. This step is required before configuring trusted publishing.
```shell
# Monorepo:
cd packages/my-first-package
bun publish --access public
# Single Package:
bun publish --access public
```
--------------------------------
### Basic Bunup Build with TypeScript
Source: https://bunup.dev/docs/advanced/programmatic-usage
Demonstrates the basic usage of the `build` function from 'bunup' in TypeScript. It shows how to import the function, call it with an entry point, and access the resulting files and build context. This function must be run within the Bun runtime.
```typescript
import { build } from 'bunup';
const result = await build({
entry: 'src/index.ts',
});
console.log('Built files:', result.files);
console.log('Build context:', result.build);
```
--------------------------------
### Specify Custom Entry Points for Declaration Generation
Source: https://bunup.dev/docs/guide/typescript-declarations
Configure which files should have declarations generated. You can specify single files, multiple files, or use glob patterns. This ensures only relevant files are processed, improving build times and output relevance. Exclusions can also be defined using the '!' prefix.
```sh
# Single entry
bunup src/index.ts src/utils.ts --dts.entry src/index.ts
# Multiple entries
bunup src/index.ts src/utils.ts src/types.ts --dts.entry src/index.ts,src/types.ts
```
```typescript
export default defineConfig({
entry: ['src/index.ts', 'src/utils.ts'],
dts: {
// Only generate declarations for index.ts
entry: ['src/index.ts'],
},
});
```
```sh
# Single glob pattern
bunup --dts.entry "src/public/**/*.ts"
# Multiple patterns (including exclusions)
bunup --dts.entry "src/public/**/*.ts,!src/public/dev/**/*"
```
```typescript
export default defineConfig({
dts: {
entry: [
'src/public/**/*.ts',
'!src/public/dev/**/*'
]
}
});
```
--------------------------------
### Run Post-build Script with Simple Command via CLI
Source: https://bunup.dev/docs/guide/options
Execute a shell command after a successful build using the '--on-success' flag with a command string.
```shell
bunup --on-success "bun run ./scripts/server.ts"
```
--------------------------------
### Make Specific Packages External with Bunup CLI
Source: https://bunup.dev/docs/guide/options
This CLI command excludes a specific package, 'lodash' in this example, from being bundled by Bunup. This allows for fine-grained control over which dependencies are externalized.
```shell
# Single package
bunup --external lodash
```
--------------------------------
### Run Post-build Script with Advanced Command Options
Source: https://bunup.dev/docs/guide/options
Execute a shell command with advanced options like working directory, environment variables, timeout, and kill signal using the 'onSuccess' object configuration.
```typescript
export default defineConfig({
onSuccess: {
cmd: 'bun run ./scripts/server.ts',
options: {
cwd: './app',
env: { ...process.env, FOO: 'bar' },
timeout: 30000, // 30 seconds
killSignal: 'SIGKILL',
},
},
});
```
--------------------------------
### Define Multiple Entry Points with Bunup CLI (Flag)
Source: https://bunup.dev/docs/guide/options
This demonstrates using the '--entry' (or '-e') flag with the Bunup CLI to specify multiple entry points. This offers a more explicit way to define multiple inputs.
```shell
bunup --entry src/index.ts --entry src/cli.ts
# or using alias
bunup -e src/index.ts -e src/cli.ts
```
--------------------------------
### Configure Bunup for Tailwind CSS Plugin
Source: https://bunup.dev/docs/recipes/react
Configures Bunup to use the Tailwind CSS plugin. This involves importing the plugin and adding it to the `plugins` array in the `bunup.config.ts` file.
```typescript
import { defineConfig } from 'bunup'
import { tailwindcss } from '@bunup/plugin-tailwindcss'
export default defineConfig({
plugins: [tailwindcss()],
})
```
--------------------------------
### Define Single Entry Point with Bunup Config
Source: https://bunup.dev/docs/guide/options
This TypeScript configuration demonstrates how to define a single entry point for Bunup using the 'entry' option in the `bunup.config.ts` file. This is equivalent to the CLI command.
```typescript
export default defineConfig({
entry: 'src/index.ts',
});
```
--------------------------------
### Enable Declaration Splitting (Bunup Config)
Source: https://bunup.dev/docs/guide/typescript-declarations
Configure declaration splitting by setting `dts.splitting: true` in your `bunup.config.ts`. This optimizes declaration files by consolidating shared types into importable chunks.
```typescript
export default defineConfig({
dts: {
splitting: true,
},
});
```
--------------------------------
### Exclude Dotfiles from Copy Operation - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Shows how to prevent dotfiles (files starting with a '.') from being copied using the `excludeDotfiles` option in the `.with()` method. Useful for omitting hidden configuration files.
```typescript
copy('assets/**/*').with({
excludeDotfiles: true
})
```
--------------------------------
### Build all packages with Bunup
Source: https://bunup.dev/docs/guide/workspaces
This command initiates a full build process for all packages defined in the Bunup workspace configuration. It utilizes the 'bunx bunup' command to execute the build. No specific package filters are applied, ensuring all projects are processed.
```shell
bunx bunup
```
--------------------------------
### Export Button Component from Entry Point
Source: https://bunup.dev/docs/recipes/react
Exports the Button component from the library's main entry point file (src/index.tsx). This makes the component available for import by consumers of the library.
```tsx
export { Button } from './components/button'
```
--------------------------------
### Enable Following Symlinks - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Demonstrates how to configure the copy plugin to follow symbolic links using the `followSymlinks` option within the `.with()` method. This ensures that linked files are copied by their target content.
```typescript
copy('assets/**/*').with({
followSymlinks: true
})
```
--------------------------------
### Enable Infer Types (Bunup Config)
Source: https://bunup.dev/docs/guide/typescript-declarations
Configure Bunup to infer types by setting `dts.inferTypes: true` in your `bunup.config.ts`. This reverts to traditional TypeScript compilation, relying on type inference for complex generics.
```typescript
export default defineConfig({
dts: {
inferTypes: true,
},
});
```
--------------------------------
### Define Single Entry Point with Bunup CLI
Source: https://bunup.dev/docs/guide/options
This CLI command specifies a single entry point file for Bunup to bundle. The output file will be named after the input file, typically placed in the 'dist' directory.
```shell
bunup src/index.ts
```
--------------------------------
### Configure React Compiler Plugin in Bunup
Source: https://bunup.dev/docs/recipes/react
Enable the React Compiler plugin by importing and adding it to the `plugins` array in your `bunup.config.ts` file. This configuration automatically optimizes your React components for better performance.
```typescript
import { defineConfig } from 'bunup'
import { reactCompiler } from '@bunup/plugin-react-compiler'
export default defineConfig({
plugins: [reactCompiler()],
})
```
--------------------------------
### Bunup Workspace with Multiple Entry Points and Configurations
Source: https://bunup.dev/docs/guide/workspaces
This TypeScript configuration for Bunup workspaces defines multiple build configurations for a 'main' package, targeting different entry points ('index.ts' and 'cli.ts') with distinct formats. Each configuration requires a 'name' for clear identification. It shows how to specify different formats (e.g., 'esm', 'cjs') and entry points for various build outputs.
```typescript
export default defineWorkspace([
{
name: "main",
root: "packages/main",
config: [
{
entry: "src/index.ts",
name: "main",
format: ["esm", "cjs"],
},
{
entry: "src/cli.ts",
name: "cli",
format: ["esm"],
},
],
},
]);
```
--------------------------------
### Cross-Compile Same Entrypoint for Multiple Targets
Source: https://bunup.dev/docs/advanced/compile
This configuration demonstrates cross-compiling the same entrypoint ('src/cli.ts') for multiple target platforms (Linux, Windows, macOS) using a build config array. Each object in the array specifies a different target, output file, and platform-specific configurations (e.g., Windows console hiding and icon).
```typescript
export default defineConfig([
{
name: 'cli-linux',
entry: 'src/cli.ts',
compile: 'bun-linux-x64',
},
{
name: 'cli-windows',
entry: 'src/cli.ts',
compile: {
target: 'bun-windows-x64',
outfile: './bin/my-app-windows.exe',
windows: {
hideConsole: true,
icon: './icon.ico',
},
},
},
{
name: 'cli-macos',
entry: 'src/cli.ts',
compile: {
target: 'bun-darwin-arm64',
outfile: './bin/my-app-macos',
},
},
]);
```
--------------------------------
### Import Tailwind CSS with Scoped Prefix
Source: https://bunup.dev/docs/recipes/react
Imports Tailwind CSS into the project using a scoped prefix to prevent class name conflicts. This allows consumers to use Tailwind without issues.
```css
@import "tailwindcss" prefix(mylib);
```
--------------------------------
### Basic Compile to Executable Configuration
Source: https://bunup.dev/docs/advanced/compile
This configuration compiles the entry point 'src/cli.ts' into a standalone executable for the current platform. The executable is output to the default 'bin/' directory.
```typescript
export default defineConfig({
entry: 'src/cli.ts',
compile: true, // Create executable for current platform
});
```
--------------------------------
### Style Button Component with Pure CSS
Source: https://bunup.dev/docs/recipes/react
Applies styling to the Button component using plain CSS. The CSS is imported directly into the component's entry point and automatically bundled by Bunup.
```css
[data-slot="button"] {
background: hsl(211, 100%, 50%);
color: white;
padding: 0.6rem 1.2rem;
border: none;
border-radius: 0.5rem;
cursor: pointer;
}
[data-slot="button"]:hover {
background: hsl(211, 100%, 45%);
}
```
--------------------------------
### Define Multiple Entry Points with Bunup Config
Source: https://bunup.dev/docs/guide/options
This TypeScript configuration shows how to define multiple entry points for Bunup by providing an array of file paths to the 'entry' option in the `bunup.config.ts` file.
```typescript
export default defineConfig({
entry: ['src/index.ts', 'src/cli.ts'],
});
```
--------------------------------
### Minified vs Original Declaration Types (TypeScript)
Source: https://bunup.dev/docs/guide/typescript-declarations
Demonstrates the difference between original and minified TypeScript declaration types. Minification shortens internal type names and removes comments for reduced file size.
```typescript
// Original:
type DeepPartial = { [P in keyof T]? : DeepPartial };
interface Response {
data: T;
error?: string;
meta?: Record;
}
declare function fetchData(url: string, options?: RequestInit): Promise>;
export { fetchData, Response, DeepPartial };
```
```typescript
// Minified:
type e={[P in keyof T]?:e};interface t{data:T;error?:string;meta?:Record;}declare function n(url:string,options?:RequestInit): Promise>;export{n as fetchData,t as Response,e as DeepPartial};
```
--------------------------------
### Minify Declaration Files (Bunup Config)
Source: https://bunup.dev/docs/guide/typescript-declarations
Enable declaration file minification by setting `dts.minify: true` in your `bunup.config.ts`. This significantly reduces file size by shortening internal type names and removing comments.
```typescript
export default defineConfig({
dts: {
minify: true,
},
});
```
--------------------------------
### Basic Minification Enable (CLI & TS)
Source: https://bunup.dev/docs/guide/options
Enable all minification options with a single flag to reduce the output file size. This is a convenient shorthand for applying common optimizations.
```sh
bunup --minify
```
```ts
export default defineConfig({
minify: true,
});
```
--------------------------------
### Compile Multiple Entrypoints to Executables
Source: https://bunup.dev/docs/advanced/compile
This configuration illustrates how to compile multiple entrypoints into separate executables. It uses a build config array, where each object defines a unique build with its own entry point and compilation settings. One entrypoint is compiled to its default executable, while the other has a custom output file name.
```typescript
export default defineConfig([
{
name: 'main',
entry: 'src/main.ts',
compile: true,
},
{
name: 'cli',
entry: 'src/cli.ts',
compile: {
outfile: 'my-cli',
},
},
]);
```
--------------------------------
### Enable Isolated Declarations in tsconfig.json
Source: https://bunup.dev/docs/guide/typescript-declarations
To enable isolated declarations, set `declaration` and `isolatedDeclarations` to `true` in your tsconfig.json. This allows for faster, file-independent declaration generation, requiring explicit return types on public exports.
```json
{
"compilerOptions": {
"declaration": true,
"isolatedDeclarations": true
}
}
```
--------------------------------
### Run Build Script from package.json
Source: https://bunup.dev/index
This command executes the build script defined in your package.json file, which is configured to run Bunup. This is a standard way to trigger builds in Node.js projects.
```shell
bun run build
```
--------------------------------
### Style Button Component with CSS Modules
Source: https://bunup.dev/docs/recipes/react
Applies styling to the Button component using CSS Modules. This provides automatic class name scoping. Styles are defined in a .module.css file and imported into the component.
```css
.button {
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
color: white;
}
.primary {
background-color: #007bff;
}
.primary:hover {
background-color: #0056b3;
}
```
--------------------------------
### Define Entry Points using Glob Patterns with Bunup CLI
Source: https://bunup.dev/docs/guide/options
This CLI command utilizes glob patterns to specify entry points for Bunup. It includes all TypeScript files while excluding test files. Patterns are resolved relative to the project root.
```shell
bunup 'src/**/*.ts' '!src/**/*.test.ts'
```
--------------------------------
### Disable Automatic Declaration File Generation
Source: https://bunup.dev/docs/guide/typescript-declarations
Completely disable Bunup's automatic generation of TypeScript declaration files. This is useful when you prefer to manage declaration generation manually or if your project does not require type definitions.
```sh
bunup --no-dts
```
```typescript
export default defineConfig({
entry: "src/index.ts",
dts: false,
});
```
--------------------------------
### Minify Declaration Files (CLI)
Source: https://bunup.dev/docs/guide/typescript-declarations
Reduce the size of generated declaration files by using the `--dts.minify` CLI flag. This shortens internal type names and removes comments while preserving public API names.
```sh
bunup --dts.minify
```
--------------------------------
### Environment Variable Handling (CLI & TS)
Source: https://bunup.dev/docs/guide/options
Manage how environment variables are handled in the bundle. Options include inlining all, disabling inlining, inlining with a prefix, or explicitly defining variables.
```sh
# Inline all environment variables available at build time
FOO=bar API_KEY=secret bunup --env inline
# Disable all environment variable inlining
bunup --env disable
# Only inline environment variables with a specific prefix (e.g., PUBLIC_)
PUBLIC_URL=https://example.com bunup --env PUBLIC_*
# Explicitly provide specific environment variables
bunup --env.NODE_ENV="production" --env.API_URL="https://api.example.com"
```
```typescript
export default defineConfig({
// Inline all available environment variables at build time
env: 'inline',
// Or disable inlining entirely (keep process.env.FOO in the output)
// env: "disable",
// Or inline only variables that start with a specific prefix
// env: "PUBLIC_*",
// Or explicitly provide specific environment variables
// These will replace both process.env.FOO and import.meta.env.FOO
// env: {
// API_URL: "https://api.example.com",
// DEBUG: "false",
// },
});
```
--------------------------------
### Watch mode for Bunup packages
Source: https://bunup.dev/docs/guide/workspaces
This command starts Bunup in watch mode, enabling automatic rebuilding of packages when changes are detected. It uses the '--watch' flag with 'bunx bunup' to monitor all workspace packages for modifications.
```shell
bunx bunup --watch
```
--------------------------------
### Multiple Copy Plugin Instances - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Illustrates using multiple instances of the copy plugin within a single Bunup configuration to perform different copy operations independently. Enhances build flexibility.
```typescript
export default defineConfig({
plugins: [
copy('README.md'),
copy('assets/**/*').to('static'),
copy('docs/**/*.md').to('documentation'),
],
});
```
--------------------------------
### Integrate Pure CSS with React Button Component
Source: https://bunup.dev/docs/recipes/react
Modifies the Button component to use a data-slot attribute for styling with Pure CSS. Also imports the global styles from styles.css in the library's entry point.
```tsx
import './styles.css'
export function Button(props: React.ComponentProps<'button'>): React.ReactNode {
return
}
```
--------------------------------
### Transform Content with Build Options - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Illustrates transforming file content and accessing build options (like `outDir` and `watch`) within the `.transform()` function. This allows for dynamic content modification based on build context.
```typescript
// Access full context including build options
copy('config/**/*')
.transform(({ content, path, destination, options }) => {
// options contains build configuration (outDir, minify, etc.)
// destination is where the file will be written
const processed = content.toString()
.replace('__BUILD_MODE__', options.watch ? 'development' : 'production')
.replace('__OUT_DIR__', options.outDir)
return processed
})
```
--------------------------------
### Enable Infer Types (CLI)
Source: https://bunup.dev/docs/guide/typescript-declarations
Switch to traditional TypeScript compilation for declaration generation using the `--dts.infer-types` CLI flag. This allows TypeScript's automatic type inference, useful for complex generic types.
```sh
bunup --dts.infer-types
```
--------------------------------
### Explicit Return Types for Public Exports (TypeScript)
Source: https://bunup.dev/docs/guide/typescript-declarations
When using isolated declarations, public exports must have explicit return types. Internal functions do not require explicit types. This practice enhances API clarity and predictability.
```typescript
// Required: Explicit return type on public exports
export function getData(): Promise {
return fetchUser();
}
// Internal functions don't need explicit types
function fetchUser() {
return api.get('/user');
}
```
--------------------------------
### Run Post-build Script with Function Callback
Source: https://bunup.dev/docs/guide/options
Execute custom JavaScript code after a successful build using a function callback in 'onSuccess'. Supports returning a cleanup function for watch mode.
```typescript
export default defineConfig({
onSuccess: (options) => {
console.log('Build completed!');
const server = startDevServer();
// Optional: return a cleanup function for watch mode
return () => server.close();
},
});
```
--------------------------------
### Define a Button Component in React
Source: https://bunup.dev/docs/recipes/react
Defines a basic Button component in TypeScript and React. This component accepts standard button props and renders a button element. It's intended to be exported from the library's entry point.
```tsx
export function Button(props: React.ComponentProps<'button'>): React.ReactNode {
return
}
```
--------------------------------
### Copy and Rename a File - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Demonstrates how to copy a file and simultaneously rename it during the process using the `.to()` method. This allows for output file name customization.
```typescript
// Copy and rename a file
copy('README.md').to('documentation.md')
```
--------------------------------
### Scoping Tailwind CSS Classes with a Prefix
Source: https://bunup.dev/docs/builtin-plugins/tailwindcss
Demonstrates how to use Tailwind's prefix feature in the main CSS file to scope class names, preventing conflicts when distributing component libraries. The example uses 'yuku' as a prefix.
```css
@import "tailwindcss" prefix(yuku);
```
--------------------------------
### Copy All Files in a Directory with Glob - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Shows how to copy all files within a specific directory, including those in subdirectories, using a glob pattern with the Bunup copy plugin.
```typescript
// Copy all files in assets directory
copy('assets/**/*')
```
--------------------------------
### Enable Declaration Splitting (CLI)
Source: https://bunup.dev/docs/guide/typescript-declarations
Enable declaration splitting using the `--dts.splitting` CLI flag. This feature prevents code duplication by extracting shared types into separate chunk files, reducing the overall size of declaration files.
```sh
bunup --dts.splitting
```
--------------------------------
### Configure Build Script in package.json
Source: https://bunup.dev/index
This JSON snippet shows how to add a 'build' script to your package.json file that executes the Bunup build command. This allows you to run builds using 'bun run build'.
```json
{
"name": "my-package",
"scripts": {
"build": "bunup"
}
}
```
--------------------------------
### Bundle All Dependencies with Bunup CLI
Source: https://bunup.dev/docs/guide/options
This CLI command instructs Bunup to bundle all declared dependencies into the output artifact using the '--packages bundle' option.
```shell
bunup --packages bundle
```
--------------------------------
### Configure Bunup to Use a Custom Plugin (TypeScript)
Source: https://bunup.dev/docs/advanced/plugin-development
Configures the Bunup build process by importing and including a custom plugin, 'myBunupPlugin', in the defineConfig options. This integrates the custom plugin's functionality into the build pipeline. Requires 'bunup' package.
```typescript
import { defineConfig } from "bunup";
import { myBunupPlugin } from "./my-bunup-plugin";
export default defineConfig({
entry: "src/index.ts",
format: ["esm", "cjs"],
plugins: [
myBunupPlugin()
]
});
```
--------------------------------
### Specify Custom Entry Points for Bunup Build
Source: https://bunup.dev/index
This command explicitly tells Bunup which files to build, overriding the default entry point detection. It's useful when you have multiple distinct entry points or want precise control over the build output.
```shell
bunx bunup src/index.ts src/plugins.ts
```
--------------------------------
### Configure Build Report Options
Source: https://bunup.dev/docs/guide/options
Customize the build report to display file sizes and compression statistics. Options include enabling/disabling reporting for Brotli and Gzip compression, and setting a maximum bundle size warning threshold. These settings are controlled via CLI flags or within the 'report' object in 'bunup.config.ts'.
```shell
# Enable brotli compression reporting (gzip is enabled by default)
bunup --report.brotli
# Set maximum bundle size warning threshold (in bytes)
bunup --report.max-bundle-size 1048576
# Disable gzip compression reporting
bunup --no-report.gzip
```
```typescript
export default defineConfig({
report: {
gzip: true, // Enable gzip size calculation (default: true)
brotli: false, // Enable brotli size calculation (default: false)
maxBundleSize: 1024 * 1024, // Warn if bundle exceeds 1MB
},
});
```
--------------------------------
### Use Scoped Tailwind CSS Classes in React Component
Source: https://bunup.dev/docs/builtin-plugins/tailwindcss
Illustrates using the prefixed Tailwind CSS classes within a React component. This ensures that the component's styles are isolated and do not interfere with the consumer's existing Tailwind setup.
```typescript
export function Button() {
return (
);
}
```
--------------------------------
### Run Development Script with Watch Mode
Source: https://bunup.dev/index
This command executes the 'dev' script defined in package.json, which is configured to run Bunup in watch mode. This enables automatic rebuilding upon file changes during development.
```shell
bun run dev
```
--------------------------------
### Define Global Constants via CLI
Source: https://bunup.dev/docs/guide/options
Define global constants that will be replaced at build time using the '--define.' flag. Values are provided as strings.
```shell
bunup --define.PACKAGE_VERSION='"1.0.0"' --define.DEBUG='false'
```
--------------------------------
### Configure CSS Injection in Bunup Configuration
Source: https://bunup.dev/docs/recipes/react
Programmatically configure Bunup to inject CSS styles into JavaScript bundles by setting the `inject` option to `true` within the `css` configuration object. This method allows for more granular control over the build process.
```typescript
import { defineConfig } from 'bunup'
export default defineConfig({
css: {
inject: true,
},
})
```
--------------------------------
### Copy and Rename a Directory - TypeScript
Source: https://bunup.dev/docs/builtin-plugins/copy
Shows how to copy a directory and change its name in the destination using the `.to()` method. This is useful for organizing build outputs.
```typescript
// Copy and rename directory
copy('assets').to('static') // ā dist/static/
```
--------------------------------
### Integrate CSS Modules with React Button Component
Source: https://bunup.dev/docs/recipes/react
Integrates CSS Modules into the Button component. It imports styles from a local CSS module file and applies scoped class names to the button element. TypeScript definitions are generated automatically.
```tsx
import styles from './button.module.css'
export function Button(props: React.ComponentProps<'button'>): React.ReactNode {
return (
)
}
```