diff --git a/code/lib/cli/src/add.ts b/code/lib/cli/src/add.ts index 7b9aca413e16..2b8565085dab 100644 --- a/code/lib/cli/src/add.ts +++ b/code/lib/cli/src/add.ts @@ -1,11 +1,6 @@ -import path from 'path'; -import fs from 'fs'; -import { sync as spawnSync } from 'cross-spawn'; - import { getStorybookInfo } from '@storybook/core-common'; import { readConfig, writeConfig } from '@storybook/csf-tools'; -import { commandLog } from './helpers'; import { JsPackageManagerFactory, useNpmWarning, @@ -15,43 +10,21 @@ import { getStorybookVersion } from './utils'; const logger = console; -const LEGACY_CONFIGS = ['addons', 'config', 'presets']; - -const postinstallAddon = async (addonName: string, isOfficialAddon: boolean) => { - let skipMsg = null; - if (!isOfficialAddon) { - skipMsg = 'unofficial addon'; - } else if (!fs.existsSync('.storybook')) { - skipMsg = 'no .storybook config'; - } else { - skipMsg = 'no codmods found'; - LEGACY_CONFIGS.forEach((config) => { - try { - const codemod = require.resolve( - // @ts-expect-error (it is broken) - `${getPackageName(addonName, isOfficialAddon)}/postinstall/${config}.js` - ); - commandLog(`Running postinstall script for ${addonName}`)(); - let configFile = path.join('.storybook', `${config}.ts`); - if (!fs.existsSync(configFile)) { - configFile = path.join('.storybook', `${config}.js`); - if (!fs.existsSync(configFile)) { - fs.writeFileSync(configFile, '', 'utf8'); - } - } - spawnSync('npx', ['jscodeshift', '-t', codemod, configFile], { - stdio: 'inherit', - shell: true, - }); - skipMsg = null; - } catch (err) { - // resolve failed, skip - } - }); - } +const postinstallAddon = async (addonName: string) => { + try { + const modulePath = require.resolve(`${addonName}/postinstall`, { paths: [process.cwd()] }); + // eslint-disable-next-line import/no-dynamic-require, global-require + const postinstall = require(modulePath); - if (skipMsg) { - commandLog(`Skipping postinstall for ${addonName}, ${skipMsg}`)(); + try { + logger.log(`Running postinstall script for ${addonName}`); + await postinstall(); + } catch (e) { + logger.error(`Error running postinstall script for ${addonName}`); + logger.error(e); + } + } catch (e) { + // no postinstall script } }; @@ -109,7 +82,7 @@ export async function add( main.appendValueToArray(['addons'], addonName); await writeConfig(main); - if (!options.skipPostinstall) { - await postinstallAddon(addon, isStorybookAddon); + if (!options.skipPostinstall && isStorybookAddon) { + await postinstallAddon(addonName); } }