Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CLI: Provide guidance for users who try to initialize Storybook on an empty dir #23874

Merged
merged 4 commits into from
Aug 24, 2023
Merged
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
28 changes: 18 additions & 10 deletions code/lib/cli/src/detect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from './project_types';
import { commandLog, isNxProject } from './helpers';
import type { JsPackageManager, PackageJsonWithMaybeDeps } from './js-package-manager';
import { HandledError } from './HandledError';

const viteConfigFiles = ['vite.config.ts', 'vite.config.js', 'vite.config.mjs'];
const webpackConfigFiles = ['webpack.config.js'];
Expand Down Expand Up @@ -135,16 +136,23 @@ export async function detectBuilder(packageManager: JsPackageManager, projectTyp
return CoreBuilder.Webpack5;
default:
// eslint-disable-next-line no-case-declarations
const { builder } = await prompts({
type: 'select',
name: 'builder',
message:
'We were not able to detect the right builder for your project. Please select one:',
choices: [
{ title: 'Vite', value: CoreBuilder.Vite },
{ title: 'Webpack 5', value: CoreBuilder.Webpack5 },
],
});
const { builder } = await prompts(
{
type: 'select',
name: 'builder',
message:
'\nWe were not able to detect the right builder for your project. Please select one:',
choices: [
{ title: 'Vite', value: CoreBuilder.Vite },
{ title: 'Webpack 5', value: CoreBuilder.Webpack5 },
],
},
{
onCancel: () => {
throw new HandledError('Canceled by the user');
},
}
);

return builder;
}
Expand Down
25 changes: 16 additions & 9 deletions code/lib/cli/src/generators/EMBER/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import { CoreBuilder } from '../../project_types';
import { baseGenerator } from '../baseGenerator';
import type { Generator } from '../types';

const generator: Generator = async (packageManager, npmOptions, options) => {
await baseGenerator(packageManager, npmOptions, options, 'ember', {
extraPackages: [
// babel-plugin-ember-modules-api-polyfill is a peerDep of @storybook/ember
'babel-plugin-ember-modules-api-polyfill',
// babel-plugin-htmlbars-inline-precompile is a peerDep of @storybook/ember
'babel-plugin-htmlbars-inline-precompile',
],
staticDir: 'dist',
});
await baseGenerator(
packageManager,
npmOptions,
{ ...options, builder: CoreBuilder.Webpack5 },
'ember',
{
extraPackages: [
// babel-plugin-ember-modules-api-polyfill is a peerDep of @storybook/ember
'babel-plugin-ember-modules-api-polyfill',
// babel-plugin-htmlbars-inline-precompile is a peerDep of @storybook/ember
'babel-plugin-htmlbars-inline-precompile',
],
staticDir: 'dist',
}
);
};

export default generator;
3 changes: 2 additions & 1 deletion code/lib/cli/src/generators/NEXTJS/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { CoreBuilder } from '../../project_types';
import { baseGenerator } from '../baseGenerator';
import type { Generator } from '../types';

const generator: Generator = async (packageManager, npmOptions, options) => {
await baseGenerator(
packageManager,
npmOptions,
options,
{ ...options, builder: CoreBuilder.Webpack5 },
'react',
{
extraAddons: ['@storybook/addon-onboarding'],
Expand Down
55 changes: 32 additions & 23 deletions code/lib/cli/src/generators/REACT_SCRIPTS/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,39 +26,48 @@ const generator: Generator = async (packageManager, npmOptions, options) => {
: {};

const craVersion = await packageManager.getPackageVersion('react-scripts');
const isCra5OrHigher = craVersion && semver.gte(craVersion, '5.0.0');
const updatedOptions = isCra5OrHigher ? { ...options, builder: CoreBuilder.Webpack5 } : options;

const extraPackages = [];
if (isCra5OrHigher) {
extraPackages.push('webpack');
// Miscellaneous dependency used in `babel-preset-react-app` but not listed as dep there
extraPackages.push('babel-plugin-named-exports-order');
// Miscellaneous dependency to add to be sure Storybook + CRA is working fine with Yarn PnP mode
extraPackages.push('prop-types');
if (craVersion === null) {
throw new Error(dedent`
It looks like you're trying to initialize Storybook in a CRA project that does not have react-scripts installed.
Please install it and make sure it's of version 5 or higher, which are the versions supported by Storybook 7.0+.
`);
}

const version = versions['@storybook/preset-create-react-app'];
const extraAddons = [
`@storybook/preset-create-react-app@${version}`,
'@storybook/addon-onboarding',
];

if (!isCra5OrHigher) {
if (!craVersion && semver.gte(craVersion, '5.0.0')) {
throw new Error(dedent`
Storybook 7.0+ doesn't support react-scripts@<5.0.0.

https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#create-react-app-dropped-cra4-support
`);
}

await baseGenerator(packageManager, npmOptions, updatedOptions, 'react', {
extraAddons,
extraPackages,
staticDir: fs.existsSync(path.resolve('./public')) ? 'public' : undefined,
skipBabel: true,
extraMain,
});
const extraPackages = [];
extraPackages.push('webpack');
// Miscellaneous dependency used in `babel-preset-react-app` but not listed as dep there
extraPackages.push('babel-plugin-named-exports-order');
// Miscellaneous dependency to add to be sure Storybook + CRA is working fine with Yarn PnP mode
extraPackages.push('prop-types');

const version = versions['@storybook/preset-create-react-app'];
const extraAddons = [
`@storybook/preset-create-react-app@${version}`,
'@storybook/addon-onboarding',
];

await baseGenerator(
packageManager,
npmOptions,
{ ...options, builder: CoreBuilder.Webpack5 },
'react',
{
extraAddons,
extraPackages,
staticDir: fs.existsSync(path.resolve('./public')) ? 'public' : undefined,
skipBabel: true,
extraMain,
}
);
};

export default generator;
13 changes: 10 additions & 3 deletions code/lib/cli/src/generators/SERVER/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { CoreBuilder } from '../../project_types';
import { baseGenerator } from '../baseGenerator';
import type { Generator } from '../types';

const generator: Generator = async (packageManager, npmOptions, options) => {
await baseGenerator(packageManager, npmOptions, options, 'server', {
extensions: ['json', 'yaml', 'yml'],
});
await baseGenerator(
packageManager,
npmOptions,
{ ...options, builder: CoreBuilder.Vite },
'server',
{
extensions: ['json', 'yaml', 'yml'],
}
);
};

export default generator;
10 changes: 9 additions & 1 deletion code/lib/cli/src/generators/SOLID/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { CoreBuilder } from '../../project_types';
import { baseGenerator } from '../baseGenerator';
import type { Generator } from '../types';

const generator: Generator = async (packageManager, npmOptions, options) => {
await baseGenerator(packageManager, npmOptions, options, 'solid', {}, 'solid');
await baseGenerator(
packageManager,
npmOptions,
{ ...options, builder: CoreBuilder.Vite },
'solid',
{},
'solid'
);
};

export default generator;
10 changes: 9 additions & 1 deletion code/lib/cli/src/generators/SVELTEKIT/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { CoreBuilder } from '../../project_types';
import { baseGenerator } from '../baseGenerator';
import type { Generator } from '../types';

const generator: Generator = async (packageManager, npmOptions, options) => {
await baseGenerator(packageManager, npmOptions, options, 'svelte', undefined, 'sveltekit');
await baseGenerator(
packageManager,
npmOptions,
{ ...options, builder: CoreBuilder.Vite },
'svelte',
undefined,
'sveltekit'
);
};

export default generator;
9 changes: 8 additions & 1 deletion code/lib/cli/src/generators/baseGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
extractEslintInfo,
suggestESLintPlugin,
} from '../automigrate/helpers/eslintPlugin';
import { detectBuilder } from '../detect';

const logger = console;

Expand Down Expand Up @@ -175,10 +176,11 @@ export async function baseGenerator(
npmOptions: NpmOptions,
{
language,
builder = CoreBuilder.Webpack5,
builder,
pnp,
frameworkPreviewParts,
yes: skipPrompts,
projectType,
}: GeneratorOptions,
renderer: SupportedRenderers,
options: FrameworkOptions = defaultOptions,
Expand All @@ -187,6 +189,11 @@ export async function baseGenerator(
const isStorybookInMonorepository = packageManager.isStorybookInMonorepo();
const shouldApplyRequireWrapperOnPackageNames = isStorybookInMonorepository || pnp;

if (!builder) {
// eslint-disable-next-line no-param-reassign
builder = await detectBuilder(packageManager, projectType);
}
ndelangen marked this conversation as resolved.
Show resolved Hide resolved

const {
extraAddons: extraAddonPackages,
extraPackages,
Expand Down
1 change: 1 addition & 0 deletions code/lib/cli/src/generators/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type GeneratorOptions = {
builder: Builder;
linkable: boolean;
pnp: boolean;
projectType: ProjectType;
frameworkPreviewParts?: FrameworkPreviewParts;
// skip prompting the user
yes: boolean;
Expand Down
75 changes: 63 additions & 12 deletions code/lib/cli/src/initiate.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-param-reassign */
import type { PackageJson } from 'read-pkg-up';
import chalk from 'chalk';
import prompts from 'prompts';
Expand All @@ -6,14 +7,9 @@ import { withTelemetry } from '@storybook/core-server';

import dedent from 'ts-dedent';
import boxen from 'boxen';
import { readdirSync } from 'fs-extra';
import { installableProjectTypes, ProjectType } from './project_types';
import {
detect,
isStorybookInstantiated,
detectLanguage,
detectBuilder,
detectPnp,
} from './detect';
import { detect, isStorybookInstantiated, detectLanguage, detectPnp } from './detect';
import { commandLog, codeLog, paddedLog } from './helpers';
import angularGenerator from './generators/ANGULAR';
import emberGenerator from './generators/EMBER';
Expand All @@ -33,10 +29,10 @@ import qwikGenerator from './generators/QWIK';
import svelteKitGenerator from './generators/SVELTEKIT';
import solidGenerator from './generators/SOLID';
import serverGenerator from './generators/SERVER';
import type { JsPackageManager } from './js-package-manager';
import type { JsPackageManager, PackageManagerName } from './js-package-manager';
import { JsPackageManagerFactory, useNpmWarning } from './js-package-manager';
import type { NpmOptions } from './NpmOptions';
import type { CommandOptions } from './generators/types';
import type { CommandOptions, GeneratorOptions } from './generators/types';
import { HandledError } from './HandledError';

const logger = console;
Expand All @@ -54,12 +50,13 @@ const installStorybook = async <Project extends ProjectType>(
const language = await detectLanguage(packageManager);
const pnp = await detectPnp();

const generatorOptions = {
const generatorOptions: GeneratorOptions = {
language,
builder: options.builder || (await detectBuilder(packageManager, projectType)),
builder: options.builder,
linkable: !!options.linkable,
pnp: pnp || options.usePnp,
yes: options.yes,
projectType: options.type,
};

const runGenerator: () => Promise<any> = async () => {
Expand Down Expand Up @@ -239,6 +236,45 @@ const projectTypeInquirer = async (
process.exit(0);
};

const getEmptyDirMessage = (packageManagerType: PackageManagerName) => {
const generatorCommandsMap = {
vite: {
npm: 'npm create vite@latest',
yarn1: 'yarn create vite',
yarn2: 'yarn create vite',
pnpm: 'pnpm create vite',
},
angular: {
npm: 'npx -p @angular/cli ng new my-project --package-manager=npm',
yarn1: 'npx -p @angular/cli ng new my-project --package-manager=yarn',
yarn2: 'npx -p @angular/cli ng new my-project --package-manager=yarn',
pnpm: 'npx -p @angular/cli ng new my-project --package-manager=pnpm',
},
};

return dedent`
Storybook cannot be installed into an empty project. We recommend creating a new project with the following:

📦 Vite CLI for React/Vue/Web Components => ${chalk.green(
generatorCommandsMap.vite[packageManagerType]
)}
See ${chalk.yellowBright('https://vitejs.dev/guide/#scaffolding-your-first-vite-project')}

📦 Angular CLI => ${chalk.green(generatorCommandsMap.angular[packageManagerType])}
See ${chalk.yellowBright('https://angular.io/cli/new')}

📦 Any other tooling of your choice

Once you've created a project, please re-run ${chalk.green(
'npx storybook@latest init'
)} inside the project root. For more information, see ${chalk.yellowBright(
'https://storybook.js.org/docs'
)}

Good luck! 🚀
`;
};

async function doInitiate(
options: CommandOptions,
pkg: PackageJson
Expand All @@ -257,6 +293,11 @@ async function doInitiate(

pkgMgr = 'npm';
}

const cwdFolderEntries = readdirSync(process.cwd());
const isEmptyDir =
cwdFolderEntries.length === 0 || cwdFolderEntries.every((entry) => entry.startsWith('.'));

const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr });
const welcomeMessage = 'storybook init - the simplest way to add a Storybook to your project.';
logger.log(chalk.inverse(`\n ${welcomeMessage} \n`));
Expand All @@ -268,6 +309,17 @@ async function doInitiate(
updateCheckInterval: 1000 * 60 * 60, // every hour (we could increase this later on.)
});

if (options.force !== true && isEmptyDir) {
logger.log(
boxen(getEmptyDirMessage(packageManager.type), {
borderStyle: 'round',
padding: 1,
borderColor: '#F1618C',
})
);
throw new HandledError('Project was initialized in an empty directory.');
}

let projectType: ProjectType;
const projectTypeProvided = options.type;
const infoText = projectTypeProvided
Expand Down Expand Up @@ -310,7 +362,6 @@ async function doInitiate(
logger.log();

if (force) {
// eslint-disable-next-line no-param-reassign
options.force = true;
} else {
process.exit(0);
Expand Down
Loading
Loading