Skip to content

Commit

Permalink
detect empty projects and provide an error message for users
Browse files Browse the repository at this point in the history
Additionally, improve the base generator when it comes to detecting builders
  • Loading branch information
yannbf committed Aug 17, 2023
1 parent 3dfc417 commit 9a4bf38
Show file tree
Hide file tree
Showing 10 changed files with 149 additions and 60 deletions.
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;
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);
}

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
52 changes: 41 additions & 11 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 @@ -36,7 +32,7 @@ import serverGenerator from './generators/SERVER';
import type { JsPackageManager } 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 @@ -257,6 +254,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 +270,35 @@ async function doInitiate(
updateCheckInterval: 1000 * 60 * 60, // every hour (we could increase this later on.)
});

if (options.force !== true && isEmptyDir) {
const emptyDirMessage = dedent`
It looks like you're trying to start a new project with Storybook inside of an empty directory. Unfortunately, Storybook doesn't work on empty projects.
Storybook needs to be installed into a project that is already set up with a framework. There are many ways to bootstrap an app in a given framework, including:
📦 Vite CLI for dozens of options: ${chalk.yellowBright(
'https://vitejs.dev/guide/#scaffolding-your-first-vite-project'
)}
📦 Start an Angular Workspace: ${chalk.yellowBright('https://angular.io/cli/new')}
📦 Start a React App: ${chalk.yellowBright(
'https://react.dev/learn/start-a-new-react-project'
)}
📦 Start a Vue App: ${chalk.yellowBright('https://vuejs.org/guide/quick-start.html')}
📦 Or any other tooling available.
Once you have setup your new project, please rerun the init command again to successfully install Storybook on your project.
For more information about installing Storybook: ${chalk.yellowBright(
'https://storybook.js.org/docs'
)}
Good luck! 🚀
`;

logger.log(
boxen(emptyDirMessage, { 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 +341,6 @@ async function doInitiate(
logger.log();

if (force) {
// eslint-disable-next-line no-param-reassign
options.force = true;
} else {
process.exit(0);
Expand Down
6 changes: 5 additions & 1 deletion code/lib/cli/src/project_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,11 @@ export const unsupportedTemplate: TemplateConfiguration = {
},
};

const notInstallableProjectTypes: ProjectType[] = [ProjectType.UNDETECTED, ProjectType.UNSUPPORTED];
const notInstallableProjectTypes: ProjectType[] = [
ProjectType.UNDETECTED,
ProjectType.UNSUPPORTED,
ProjectType.NX,
];

export const installableProjectTypes = Object.values(ProjectType)
.filter((type) => !notInstallableProjectTypes.includes(type))
Expand Down

0 comments on commit 9a4bf38

Please sign in to comment.