Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
43 changes: 0 additions & 43 deletions packages/cli/binding/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,13 +419,6 @@ pub async fn main<
let workspace = Workspace::partial_load(cwd.clone())?;
let lib_fn =
options.map(|o| o.lib).expect("lib command requires CliOptions to be provided");
let lib_config_path = workspace.cache_path().join("vite-lib.config.js");
if write_vite_lib_config(&cwd, &lib_config_path).await? {
args.extend_from_slice(&[
"--config".to_string(),
lib_config_path.as_path().to_string_lossy().into_owned(),
]);
}
let summary = lib(lib_fn, &workspace, args).await?;
workspace.unload().await?;
summary
Expand Down Expand Up @@ -574,42 +567,6 @@ async fn read_vite_config_from_workspace_root<
Ok(None)
}

async fn write_vite_lib_config(
workspace_root: &AbsolutePathBuf,
lib_config_path: &AbsolutePathBuf,
) -> Result<bool, Error> {
let relative_vite_config_path =
lib_config_path.strip_prefix(workspace_root).map_err(|e| Error::InvalidRelativePath {
path: e.stripped_path.into(),
reason: e.invalid_path_data_error.into(),
})?;
if let Some(relative_vite_config_path) = relative_vite_config_path {
let relative_prefix = relative_vite_config_path
.as_path()
.components()
.skip(1)
.map(|_| "..".to_string())
.collect::<Vec<_>>()
.join("/");
write(
&lib_config_path,
format!(
r#"let config
try {{
const viteConfig = await import('{relative_prefix}/vite.config.ts')
config = viteConfig.default.lib
}} catch {{
}}
export default config
"#
),
)
.await?;
return Ok(true);
}
Ok(false)
}

#[cfg(test)]
mod tests {
use clap::Parser;
Expand Down
1 change: 1 addition & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"dependencies": {
"@voidzero-dev/vite-plus-core": "workspace:*",
"@voidzero-dev/vite-plus-test": "workspace:*",
"cac": "catalog:",
"oxfmt": "catalog:",
"oxlint": "catalog:",
"oxlint-tsgolint": "catalog:"
Expand Down
21 changes: 10 additions & 11 deletions packages/cli/snap-tests/command-helper/snap.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,36 +26,34 @@ Options:
-V, --version Print version

> vite lib -h # lib help message
tsdown/<semver>
vite lib

Usage:
$ tsdown [...files]
$ vite lib [...files]

Commands:
[...files] Bundle files
migrate Migrate from tsup to tsdown

For more info, run any command with the `--help` flag:
$ tsdown --help
$ tsdown migrate --help
$ vite lib --help

Options:
-c, --config <filename> Use a custom config file
--config-loader <loader> Config loader to use: auto, native, unrun (default: auto)
--no-config Disable config file (default: true)
-f, --format <format> Bundle format: esm, cjs, iife, umd (default: esm)
--clean Clean output directory, --no-clean to disable
--external <module> Mark dependencies as external
--minify Minify output
--debug Enable debug mode
--debug-logs [feat] Show debug logs
--devtools Enable devtools integration
--debug [feat] Show debug logs
--target <target> Bundle target, e.g "es2015", "esnext"
-l, --logLevel <level> Set log level: info, warn, error, silent
--fail-on-warn Fail on warnings (default: true)
--no-write Disable writing files to disk, incompatible with watch mode (default: true)
-d, --out-dir <dir> Output directory (default: dist)
--treeshake Tree-shake bundle (default: true)
--sourcemap Generate source map (default: false)
--shims Enable cjs and esm shims (default: false)
--shims Enable cjs and esm shims (default: false)
--platform <platform> Target platform (default: node)
--dts Generate dts files
--publint Enable publint (default: false)
Expand All @@ -66,16 +64,17 @@ Options:
--from-vite [vitest] Reuse config from Vite or Vitest
--report Size report (default: true)
--env.* <value> Define compile-time env variables
--env-file <file> Load environment variables from a file, when used together with --env, variables in --env take precedence
--env-prefix <prefix> Prefix for env variables to inject into the bundle (default: VITE_LIB_,TSDOWN_)
--on-success <command> Command to run on success
--copy <dir> Copy files to output dir
--public-dir <dir> Alias for --copy, deprecated
--tsconfig <tsconfig> Set tsconfig path
--unbundle Unbundle mode
-W, --workspace [dir] Enable workspace mode
-F, --filter <pattern> Filter workspace packages, e.g. /regex/ or substring
-F, --filter <pattern> Filter configs (cwd or name), e.g. /pkg-name$/ or pkg-name
--exports Generate export-related metadata for package.json (experimental)
-h, --help Display this message
-v, --version Display version number


> vite fmt -h # fmt help message
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default {
lib: {
entry: 'src/index.ts',
format: ['cjs'],
},
};
4 changes: 0 additions & 4 deletions packages/cli/snap-tests/command-lib-monorepo/snap.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
> vite run hello#build # should build the library
~/packages/hello$ vite lib
ℹ tsdown v<semver> powered by rolldown v<semver>
ℹ Using tsdown config: <cwd>/packages/hello/tsdown.config.ts
ℹ entry: src/index.ts
ℹ Build start
ℹ dist/index.cjs <variable> kB │ gzip: <variable> kB
Expand All @@ -28,8 +26,6 @@ index.cjs

> vite run hello#build # should hit cache
~/packages/hello$ vite lib (✓ cache hit, replaying)
ℹ tsdown v<semver> powered by rolldown v<semver>
ℹ Using tsdown config: <cwd>/packages/hello/tsdown.config.ts
ℹ entry: src/index.ts
ℹ Build start
ℹ dist/index.cjs <variable> kB │ gzip: <variable> kB
Expand Down
25 changes: 10 additions & 15 deletions packages/cli/snap-tests/command-lib/snap.txt
Original file line number Diff line number Diff line change
@@ -1,34 +1,32 @@
> vite lib -h # should print the help message
tsdown/<semver>
vite lib

Usage:
$ tsdown [...files]
$ vite lib [...files]

Commands:
[...files] Bundle files
migrate Migrate from tsup to tsdown

For more info, run any command with the `--help` flag:
$ tsdown --help
$ tsdown migrate --help
$ vite lib --help

Options:
-c, --config <filename> Use a custom config file
--config-loader <loader> Config loader to use: auto, native, unrun (default: auto)
--no-config Disable config file (default: true)
-f, --format <format> Bundle format: esm, cjs, iife, umd (default: esm)
--clean Clean output directory, --no-clean to disable
--external <module> Mark dependencies as external
--minify Minify output
--debug Enable debug mode
--debug-logs [feat] Show debug logs
--devtools Enable devtools integration
--debug [feat] Show debug logs
--target <target> Bundle target, e.g "es2015", "esnext"
-l, --logLevel <level> Set log level: info, warn, error, silent
--fail-on-warn Fail on warnings (default: true)
--no-write Disable writing files to disk, incompatible with watch mode (default: true)
-d, --out-dir <dir> Output directory (default: dist)
--treeshake Tree-shake bundle (default: true)
--sourcemap Generate source map (default: false)
--shims Enable cjs and esm shims (default: false)
--shims Enable cjs and esm shims (default: false)
--platform <platform> Target platform (default: node)
--dts Generate dts files
--publint Enable publint (default: false)
Expand All @@ -39,21 +37,20 @@ Options:
--from-vite [vitest] Reuse config from Vite or Vitest
--report Size report (default: true)
--env.* <value> Define compile-time env variables
--env-file <file> Load environment variables from a file, when used together with --env, variables in --env take precedence
--env-prefix <prefix> Prefix for env variables to inject into the bundle (default: VITE_LIB_,TSDOWN_)
--on-success <command> Command to run on success
--copy <dir> Copy files to output dir
--public-dir <dir> Alias for --copy, deprecated
--tsconfig <tsconfig> Set tsconfig path
--unbundle Unbundle mode
-W, --workspace [dir] Enable workspace mode
-F, --filter <pattern> Filter workspace packages, e.g. /regex/ or substring
-F, --filter <pattern> Filter configs (cwd or name), e.g. /pkg-name$/ or pkg-name
--exports Generate export-related metadata for package.json (experimental)
-h, --help Display this message
-v, --version Display version number


> vite lib src/index.ts # should build the library
ℹ tsdown v<semver> powered by rolldown v<semver>
ℹ Using tsdown config: <cwd>/node_modules/.vite/task-cache/vite-lib.config.js
ℹ entry: src/index.ts
ℹ Build start
ℹ dist/index.mjs <variable> kB │ gzip: <variable> kB
Expand All @@ -66,8 +63,6 @@ index.mjs

> vite lib src/index.ts # should hit cache
✓ cache hit, replaying
ℹ tsdown v<semver> powered by rolldown v<semver>
ℹ Using tsdown config: <cwd>/node_modules/.vite/task-cache/vite-lib.config.js
ℹ entry: src/index.ts
ℹ Build start
ℹ dist/index.mjs <variable> kB │ gzip: <variable> kB
Expand Down
98 changes: 98 additions & 0 deletions packages/cli/src/lib-bin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/env node
import module from 'node:module';

import { resolveConfig } from '@voidzero-dev/vite-plus-core';
import { build, type UserConfig, globalLogger } from '@voidzero-dev/vite-plus-core/lib';
import { cac } from 'cac';

const cli = cac('vite lib');
cli.help();

const DEFAULT_ENV_PREFIXES = ['VITE_LIB_', 'TSDOWN_'];

cli
.command('[...files]', 'Bundle files', {
ignoreOptionDefaultValue: true,
allowUnknownOptions: true,
})
// Only support config file in vite.config.ts
// .option('-c, --config <filename>', 'Use a custom config file')
Comment thread
fengmk2 marked this conversation as resolved.
.option('--config-loader <loader>', 'Config loader to use: auto, native, unrun', {
default: 'auto',
})
Comment thread
fengmk2 marked this conversation as resolved.
.option('--no-config', 'Disable config file')
.option('-f, --format <format>', 'Bundle format: esm, cjs, iife, umd', {
default: 'esm',
})
.option('--clean', 'Clean output directory, --no-clean to disable')
.option('--external <module>', 'Mark dependencies as external')
.option('--minify', 'Minify output')
.option('--devtools', 'Enable devtools integration')
.option('--debug [feat]', 'Show debug logs')
.option('--target <target>', 'Bundle target, e.g "es2015", "esnext"')
.option('-l, --logLevel <level>', 'Set log level: info, warn, error, silent')
.option('--fail-on-warn', 'Fail on warnings', { default: true })
.option('--no-write', 'Disable writing files to disk, incompatible with watch mode')
.option('-d, --out-dir <dir>', 'Output directory', { default: 'dist' })
.option('--treeshake', 'Tree-shake bundle', { default: true })
.option('--sourcemap', 'Generate source map', { default: false })
.option('--shims', 'Enable cjs and esm shims', { default: false })
.option('--platform <platform>', 'Target platform', {
default: 'node',
})
.option('--dts', 'Generate dts files')
.option('--publint', 'Enable publint', { default: false })
.option('--attw', 'Enable Are the types wrong integration', {
default: false,
})
.option('--unused', 'Enable unused dependencies check', { default: false })
.option('-w, --watch [path]', 'Watch mode')
.option('--ignore-watch <path>', 'Ignore custom paths in watch mode')
.option('--from-vite [vitest]', 'Reuse config from Vite or Vitest')
.option('--report', 'Size report', { default: true })
.option('--env.* <value>', 'Define compile-time env variables')
.option(
'--env-file <file>',
'Load environment variables from a file, when used together with --env, variables in --env take precedence',
)
.option('--env-prefix <prefix>', 'Prefix for env variables to inject into the bundle', {
// support `TSDOWN_` for migration compatibility
default: DEFAULT_ENV_PREFIXES,
})
Comment thread
fengmk2 marked this conversation as resolved.
.option('--on-success <command>', 'Command to run on success')
.option('--copy <dir>', 'Copy files to output dir')
.option('--public-dir <dir>', 'Alias for --copy, deprecated')
.option('--tsconfig <tsconfig>', 'Set tsconfig path')
.option('--unbundle', 'Unbundle mode')
.option('-W, --workspace [dir]', 'Enable workspace mode')
.option('-F, --filter <pattern>', 'Filter configs (cwd or name), e.g. /pkg-name$/ or pkg-name')
.option('--exports', 'Generate export-related metadata for package.json (experimental)')
.action(async (input: string[], flags: UserConfig) => {
const viteConfig = await resolveConfig({ root: process.cwd() }, 'build');
if (input.length > 0) flags.entry = input;
// TODO: set default envPrefix after tsdown upgrade
await build({
...(viteConfig.lib as UserConfig),
Comment thread
fengmk2 marked this conversation as resolved.
...flags,
config: false,
Comment thread
fengmk2 marked this conversation as resolved.
});
});

export async function runCLI(): Promise<void> {
cli.parse(process.argv, { run: false });

// TODO: enable debug after tsdown upgrade
// enableDebug(cli.options)
Comment thread
fengmk2 marked this conversation as resolved.

try {
await cli.runMatchedCommand();
} catch (error: any) {
globalLogger.error(String(error.stack || error.message));
Comment thread
fengmk2 marked this conversation as resolved.
process.exit(1);
}
}

if (module.enableCompileCache) {
module.enableCompileCache();
}
runCLI();
11 changes: 3 additions & 8 deletions packages/cli/src/resolve-lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
* Used for: `vite-plus lib` command
*/

import { dirname, join } from 'node:path';
import { join } from 'node:path';

import { DEFAULT_ENVS, resolve } from './utils.js';
import { DEFAULT_ENVS } from './utils.js';

/**
* Resolves the Tsdown binary path and environment variables.
Expand All @@ -26,12 +26,7 @@ export async function lib(): Promise<{
envs: Record<string, string>;
}> {
// Resolve the bundled Tsdown CLI
const binPath = join(
dirname(resolve('@voidzero-dev/vite-plus-core/package.json')),
'dist',
'tsdown',
'run.js',
);
const binPath = join(import.meta.dirname, 'lib-bin.js');
Comment thread
fengmk2 marked this conversation as resolved.

return {
binPath,
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ catalog:
acorn: ^8.12.1
astring: ^1.9.0
buble: ^0.20.0
cac: ^6.7.14
chalk: ^5.3.0
change-case: ^5.4.4
connect: ^3.7.0
Expand Down
Loading