Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions docs/guide/migrate-from-unbuild.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Migrate from unbuild

[unbuild](https://github.com/unjs/unbuild) is a popular unified JavaScript build system from the unjs ecosystem. If you're currently using `unbuild` and want to migrate to `tsdown`, the process is straightforward thanks to the dedicated `migrate` command with the `--from unbuild` option:

```bash
npx tsdown migrate --from unbuild
```

> [!WARNING]
> Please save your changes before migration. The migration process may modify your configuration files, so it's important to ensure all your changes are committed or backed up beforehand.

## What Gets Migrated

The migration process handles:

1. **Package.json** changes:
- Dependencies: Updates `unbuild` dependencies to `tsdown`
- Scripts: Updates any scripts using `unbuild` to use `tsdown` instead
- Configuration: Migrates any `unbuild` configuration in package.json to `tsdown` format

2. **Config Files**:
- Converts `build.config.*` files to `tsdown.config.*` files
- Updates imports from `unbuild` to `tsdown`
- Transforms `defineBuildConfig` to `defineConfig`
- Adapts build configuration options to match tsdown equivalents

## Migration Options

The `migrate` command supports the following options to customize the migration process:

- `--cwd <dir>` (or `-c`): Specify the working directory for the migration.
- `--dry-run` (or `-d`): Perform a dry run to preview the migration without making any changes.
- `--from <source>`: Specify the source bundler to migrate from (defaults to `tsup`, use `unbuild` for unbuild migration).

With these options, you can easily tailor the migration process to fit your specific project setup.

## Differences from unbuild

While `tsdown` aims to provide a smooth migration experience from `unbuild`, there are some notable differences to be aware of:

1. **Configuration Format**: tsdown uses a slightly different configuration format. The migration script handles most common options, but you may need to manually adjust some advanced configurations.

2. **Builders**: unbuild's `mkdist` builder is mapped to tsdown's `dts` builder, but there might be slight differences in behavior.

3. **Rollup vs Rolldown**: unbuild uses Rollup, whereas tsdown uses [Rolldown](https://rolldown.rs/), a Rust-based bundler that's faster and more efficient.

After migration, it's recommended to review your configuration and build output to ensure everything is working as expected.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
"prettier": "catalog:dev",
"publint": "catalog:dev",
"tsup": "catalog:dev",
"unbuild": "catalog:prod",
"tsx": "catalog:dev",
"typedoc": "catalog:docs",
"typedoc-plugin-markdown": "catalog:docs",
Expand Down
1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ catalogs:
tinyglobby: ^0.2.13
unconfig: ^7.3.2
unplugin-lightningcss: ^0.3.3
unbuild: ^3.5.0

ignoredBuiltDependencies:
- rolldown
Expand Down
5 changes: 4 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,12 @@ cli
})

cli
.command('migrate', 'Migrate from tsup to tsdown')
.command('migrate', 'Migrate from tsup or unbuild to tsdown')
.option('-c, --cwd <dir>', 'Working directory')
.option('-d, --dry-run', 'Dry run')
.option('--from <source>', 'Source bundler (tsup or unbuild)', {
default: 'tsup',
})
.action(async (args) => {
const { migrate } = await import('./migrate')
await migrate(args)
Expand Down
184 changes: 184 additions & 0 deletions src/migrate-unbuild.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import { existsSync } from 'node:fs'
import { readFile, unlink, writeFile } from 'node:fs/promises'
import process from 'node:process'
import consola from 'consola'
import { version } from '../package.json'

export async function migrateFromUnbuild({
cwd,
dryRun,
}: {
cwd?: string
dryRun?: boolean
}): Promise<void> {
if (dryRun) {
consola.info('Dry run enabled. No changes were made.')
} else {
const confirm = await consola.prompt(
'Please make sure to commit your changes before migrating. Continue?',
{ type: 'confirm' },
)
if (!confirm) {
consola.error('Migration cancelled.')
process.exitCode = 1
return
}
}

if (cwd) process.chdir(cwd)

let migrated = await migratePackageJson(dryRun)
if (await migrateUnbuildConfig(dryRun)) {
migrated = true
}
if (migrated) {
consola.success(
'Migration completed. Remember to run install command with your package manager.',
)
} else {
consola.error('No migration performed.')
process.exitCode = 1
}
}

async function migratePackageJson(dryRun?: boolean): Promise<boolean> {
if (!existsSync('package.json')) {
consola.error('No package.json found')
return false
}

const pkgRaw = await readFile('package.json', 'utf-8')
let pkg = JSON.parse(pkgRaw)
const semver = `^${version}`
let found = false
if (pkg.dependencies?.unbuild) {
consola.info('Migrating `dependencies` to tsdown.')
found = true
pkg.dependencies = renameKey(pkg.dependencies, 'unbuild', 'tsdown', semver)
}
if (pkg.devDependencies?.unbuild) {
consola.info('Migrating `devDependencies` to tsdown.')
found = true
pkg.devDependencies = renameKey(
pkg.devDependencies,
'unbuild',
'tsdown',
semver,
)
}
if (pkg.peerDependencies?.unbuild) {
consola.info('Migrating `peerDependencies` to tsdown.')
found = true
pkg.peerDependencies = renameKey(
pkg.peerDependencies,
'unbuild',
'tsdown',
'*',
)
}
if (pkg.scripts) {
for (const key of Object.keys(pkg.scripts)) {
if (pkg.scripts[key].includes('unbuild')) {
consola.info(`Migrating \`${key}\` script to tsdown`)
found = true
pkg.scripts[key] = pkg.scripts[key].replaceAll(
/unbuild(?:-node)?/g,
'tsdown',
)
}
}
}
if (pkg.unbuild) {
consola.info('Migrating `unbuild` field in package.json to `tsdown`.')
found = true
pkg = renameKey(pkg, 'unbuild', 'tsdown')
}

if (!found) {
consola.warn('No unbuild-related fields found in package.json')
return false
}

const pkgStr = `${JSON.stringify(pkg, null, 2)}\n`
if (dryRun) {
const { createPatch } = await import('diff')
consola.info('[dry-run] package.json:')
console.info(createPatch('package.json', pkgRaw, pkgStr))
} else {
await writeFile('package.json', pkgStr)
consola.success('Migrated `package.json`')
}
return true
}

const UNBUILD_CONFIG_FILES = [
'build.config.ts',
'build.config.cts',
'build.config.mts',
'build.config.js',
'build.config.cjs',
'build.config.mjs',
'build.config.json',
]

async function migrateUnbuildConfig(dryRun?: boolean): Promise<boolean> {
let found = false

for (const file of UNBUILD_CONFIG_FILES) {
if (!existsSync(file)) continue
consola.info(`Found \`${file}\``)
found = true

const unbuildConfigRaw = await readFile(file, 'utf-8')

// Replace unbuild imports with tsdown
let tsdownConfig = unbuildConfigRaw
.replace(/from ["']unbuild["']/g, 'from "tsdown"')
.replace(/import\s*{\s*defineBuildConfig\s*}/g, 'import { defineConfig }')
.replace(/defineBuildConfig\(/g, 'defineConfig(')

// Replace unbuild specific options with tsdown equivalents
// This is a simplified approach - might need to be expanded based on actual options mapping
tsdownConfig = tsdownConfig
.replace(/builder:\s*["']mkdist["']/g, 'builder: "dts"')
.replace(/rollup:/g, 'rolldown:')

const tsdownFileName = file.replace('build.config', 'tsdown.config');

if (dryRun) {
const { createTwoFilesPatch } = await import('diff')
consola.info(`[dry-run] ${file} -> ${tsdownFileName}:`)
console.info(
createTwoFilesPatch(file, tsdownFileName, unbuildConfigRaw, tsdownConfig),
)
} else {
await writeFile(tsdownFileName, tsdownConfig, 'utf8')
await unlink(file)
consola.success(`Migrated \`${file}\` to \`${tsdownFileName}\``)
}
}

if (!found) {
consola.warn('No unbuild config found')
}

return found
}

// rename key but keep order
function renameKey(
obj: Record<string, any>,
oldKey: string,
newKey: string,
newValue?: any,
) {
const newObj: Record<string, any> = {}
for (const key of Object.keys(obj)) {
if (key === oldKey) {
newObj[newKey] = newValue || obj[oldKey]
} else {
newObj[key] = obj[key]
}
}
return newObj
}
8 changes: 8 additions & 0 deletions src/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,22 @@ import { readFile, unlink, writeFile } from 'node:fs/promises'
import process from 'node:process'
import consola from 'consola'
import { version } from '../package.json'
import { migrateFromUnbuild } from './migrate-unbuild'

export async function migrate({
cwd,
dryRun,
from,
}: {
cwd?: string
dryRun?: boolean
from?: 'tsup' | 'unbuild'
}): Promise<void> {
if (from === 'unbuild') {
return migrateFromUnbuild({ cwd, dryRun })
}

// Default to tsup migration
if (dryRun) {
consola.info('Dry run enabled. No changes were made.')
} else {
Expand Down