Skip to content

Commit

Permalink
feat: check if dist folder is empty before previewing (#2460)
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan authored May 29, 2024
1 parent 18f603e commit 085c2f0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
25 changes: 19 additions & 6 deletions packages/core/src/cli/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { type RsbuildMode, color, logger } from '@rsbuild/shared';
import { type Command, program } from '../../compiled/commander/index.js';
import { isEmptyDir } from '../helpers';
import { init } from './init';

export type CommonOptions = {
Expand Down Expand Up @@ -94,12 +95,24 @@ export function runCli() {
try {
const rsbuild = await init({ cliOptions: options });

if (rsbuild && !existsSync(rsbuild.context.distPath)) {
throw new Error(
`The output directory ${color.yellow(
rsbuild.context.distPath,
)} does not exist, please build the project before previewing.`,
);
if (rsbuild) {
const { distPath } = rsbuild.context;

if (!existsSync(distPath)) {
throw new Error(
`The output directory ${color.yellow(
distPath,
)} does not exist, please build the project before previewing.`,
);
}

if (isEmptyDir(distPath)) {
throw new Error(
`The output directory ${color.yellow(
distPath,
)} is empty, please build the project before previewing.`,
);
}
}

await rsbuild?.preview();
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,11 @@ export const isFileSync = (filePath: string) => {
}
};

export function isEmptyDir(path: string) {
const files = fse.readdirSync(path);
return files.length === 0 || (files.length === 1 && files[0] === '.git');
}

/**
* Find first already exists file.
* @param files - Absolute file paths with extension.
Expand Down

0 comments on commit 085c2f0

Please sign in to comment.