Skip to content
This repository has been archived by the owner on Mar 6, 2024. It is now read-only.

[FEEDBACK] Auto configuration scripts #49

Open
ShaunEvening opened this issue Jun 7, 2023 · 22 comments
Open

[FEEDBACK] Auto configuration scripts #49

ShaunEvening opened this issue Jun 7, 2023 · 22 comments
Labels
help wanted Extra attention is needed

Comments

@ShaunEvening
Copy link
Contributor

ShaunEvening commented Jun 7, 2023

What?

As of version 1.1.0, I have introduced codemod scripts to auto-configure the styling addon for users of the following styling tools:

  • Tailwind
  • Material UI
  • Styled-components
  • Emotion

The codemod didn't work for me! Now what?

Apologies for not being able to get it right for your project, I'm working on it 🙏

Please leave me the following details about your project:

  1. Storybook version
  2. @storybook/addon-styling version
  3. Contents of your main.ts or main.js file
  4. Contents of your preview.ts or preview.js file
  5. The tool you wanted to auto-configure (Tailwind or Material UI)
@ShaunEvening ShaunEvening added the help wanted Extra attention is needed label Jun 7, 2023
@TroyMorvant
Copy link

TroyMorvant commented Jun 15, 2023

Tried it with the following stack without success:

node node_modules/@storybook/addon-styling/bin/postinstall.js

=========================================

 🧰 Configuring @storybook/addon-styling

=========================================

📣 No supported tool detected. Skipping auto-configuration.
      
  Check out the documentation for how to manually configure the addon.
  https://storybook.js.org/addons/@storybook/addon-styling/

build system: NX
bundler: Vite
compiler: SWC

@storybook: ^7.0.9
@storybook/addon-styling: ^1.3.0


   Node   : 18.16.0
   OS     : darwin arm64
   yarn   : 1.22.19
   Hasher : Native
   
   nx                 : 16.3.2
   @nx/js             : 16.3.2
   @nx/jest           : 16.3.2
   @nx/linter         : 16.3.2
   @nx/workspace      : 16.3.2
   @nx/cypress        : 16.3.2
   @nx/devkit         : 16.3.2
   @nx/eslint-plugin  : 16.3.2
   @nx/nest           : 16.3.2
   @nx/node           : 16.3.2
   @nx/react          : 16.3.2
   @nx/rollup         : 16.3.2
   @nx/storybook      : 16.3.2
   @nrwl/tao          : 16.3.2
   @nx/vite           : 16.3.2
   @nx/web            : 16.3.2
   @nx/webpack        : 16.3.2
   nx-cloud           : 16.0.5
   typescript         : 5.0.4
   ---------------------------------------

main.ts

import type { StorybookConfig } from '@storybook/react-vite';
import { mergeConfig } from 'vite';
import { resolve } from 'path';

const config: StorybookConfig = {
  stories: ['../src/**/*.stories.@(js|jsx|ts|tsx|mdx)'],
  addons: ['@storybook/addon-essentials'],
  framework: {
    name: '@storybook/react-vite',
    options: {
      builder: {
        viteConfigPath: './packages/components/vite.config.ts',
      },
    },
  },
  viteFinal: async (config, { configType }) => {
    console.log(__dirname);
    return mergeConfig(config, {
      resolve: {
        alias: {
          '@cold/components': resolve(__dirname, '../../components/src'),
          '@cold/components/interfaces': resolve(__dirname, '../../components/src/interfaces'),
          '@cold/components/assets': resolve(__dirname, '../../components/src/assets'),
          '@cold/components/lib': resolve(__dirname, '../../components/src/lib'),
          '@cold/components/fetchers': resolve(__dirname, '../../components/src/fetchers'),
          '@cold/components/atomic': resolve(__dirname, '../../components/src/atomic'),
          '@cold/components/molecular': resolve(__dirname, '../../components/src/molecular'),
          '@cold/components/enums': resolve(__dirname, '../../components/src/enums'),
          '@cold/components/themes': resolve(__dirname, '../../components/src/themes'),
          '@cold/components/styles': resolve(__dirname, '../../components/src/styles/globals.css'),
          '@cold/components/mocks': resolve(__dirname, '../../components/src/__mocks__'),
        },
      },
    });
  },
};

preview.ts

import type { Preview } from "@storybook/react";

const preview: Preview = {
  parameters: {
    actions: { argTypesRegex: "^on[A-Z].*" },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
  },
};

export default preview;

@kylesuss
Copy link

kylesuss commented Jun 15, 2023

Sup @integrayshaun 😄

I just gave this a whirl on a new project.

  1. "@storybook/react": "7.0.21"
  2. "@storybook/addon-styling": "1.3.0"
  3. main.js:
import type { StorybookConfig } from '@storybook/nextjs';

const config: StorybookConfig = {
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    '@storybook/addon-styling',
  ],
  framework: {
    name: '@storybook/nextjs',
    options: {},
  },
  docs: {
    autodocs: 'tag',
  },
  staticDirs: ['../public'],
};

export default config;
  1. preview.js:
import type { Preview } from '@storybook/react';
import '../src/styles/globals.scss';

const preview: Preview = {
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      hideNoControlsWarning: true,
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
  },
};

export default preview;
  1. Tailwind!

Here's the error I see:

TypeError: Cannot read properties of undefined (reading 'tailwindcss')
    at zy (/Users/kyle/Code/app/node_modules/@storybook/addon-styling/bin/postinstall.js:950:43083)
    at EFr (/Users/kyle/Code/app/node_modules/@storybook/addon-styling/bin/postinstall.js:950:43456)
    at /Users/kyle/Code/app/node_modules/@storybook/addon-styling/bin/postinstall.js:1060:205
    at Array.find (<anonymous>)
    at wFr (/Users/kyle/Code/app/node_modules/@storybook/addon-styling/bin/postinstall.js:1060:183)
    at kFr (/Users/kyle/Code/app/node_modules/@storybook/addon-styling/bin/postinstall.js:1066:18)
    at Object.<anonymous> (/Users/kyle/Code/app/node_modules/@storybook/addon-styling/bin/postinstall.js:1069:1091)
    at Module._compile (node:internal/modules/cjs/loader:1275:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Module.load (node:internal/modules/cjs/loader:1133:32)

I should note that I am using a Yarn workspace & running the script from the project root. That's where the node module is stored so that seemed to make sense.

Let me know if you need any other details to troubleshoot. Cheers ✌️

@ShaunEvening
Copy link
Contributor Author

Hey @TroyMorvant 👋

What tool were you hoping to get configured?

Right now we only support Tailwind, material UI, styled-components, and Emotion.

@ShaunEvening
Copy link
Contributor Author

Hey @kylesuss 👋

This checks out as I haven't had a ton of time to work through the monorepos or yarn workspaces 😅

Any chance you can share the repo or a barebones reproduction of it for me to test with?

The error you're getting for tailwind here is that it can't find a dependencies or devDependencies map in the package.json it found which i'll make sure to catch in a patch 🥳

@kylesuss
Copy link

kylesuss commented Jun 15, 2023

@integrayshaun no sweat, I know it's not the first use case to consider 😄

Anyways, here's a repro:

https://github.com/kylesuss/sb-addon-styling-repro

Some of the packages that the script adds are still in there as I added them manually but the issue remains with the postinstall script from the docs!

@eilinora
Copy link

Tried this out as well today. And received an error

"@storybook/react": "7.0.21"
"@storybook/addon-docs": "^7.0.21"
"@storybook/addon-essentials": "^7.0.21"
"@storybook/addon-styling": "^1.3.0"

main.ts

const config = {
  core: {
    builder: 'webpack5',
  },
  reactOptions: { fastRefresh: true },
  framework: {
    name: '@storybook/react-webpack5',
    options: {},
  },
  stories: [
    '../src/**/*.mdx',
    '../src/**/*.stories.mdx',
    '../src/**/*.stories.@(js|jsx|ts|tsx)',
  ],
  addons: [
    '@storybook/addon-essentials',
    '@nrwl/react/plugins/storybook',
    '@storybook/addon-docs',
    '@storybook/addon-styling',
  ],
  docs: {
    autodocs: true,
  },
};
module.exports = config;

// To customize your webpack configuration you can use the webpackFinal field.
// Check https://storybook.js.org/docs/react/builders/webpack#extending-storybooks-webpack-config
// and https://nx.dev/packages/storybook/documents/custom-builder-configs

Error

› node node_modules/@storybook/addon-styling/bin/postinstall.js

=========================================

 🧰 Configuring @storybook/addon-styling

=========================================

node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: ENOENT: no such file or directory, open '.storybook/main.js'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '.storybook/main.js'
}

Node.js v18.14.1

@ShaunEvening
Copy link
Contributor Author

Hey @eilinora

Can you give me a little more information about your project? it looks like you're using NX to manage a monorepo?

Also, what tool are you trying to configure?

@oliviervanbulck
Copy link

Tried it, but it failed.

(2/3) .storybook/main.ts
  • Registering @storybook/addon-styling.
    • Configuring postcss.
node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:        

  assert_1.default.ok(lines instanceof linesModule.Lines)

    at new Patcher (C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\node_modules\recast\lib\patcher.js:20:22)
    at C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\node_modules\recast\lib\patcher.js:138:23
    at print (C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\node_modules\recast\lib\printer.js:76:17)
    at C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\node_modules\recast\lib\printer.js:49:41
    at printComments (C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\node_modules\recast\lib\comments.js:287:22)
    at print (C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\node_modules\recast\lib\printer.js:55:49)
    at Printer.print (C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\node_modules\recast\lib\printer.js:88:21)
    at Object.print (C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\node_modules\recast\main.js:31:43)
    at JEr (C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\bin\postinstall.js:950:42521)
    at afe (C:\Users\vanbuol\Projects\rex-frontend\node_modules\@storybook\addon-styling\bin\postinstall.js:950:42842) {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: '=='
}

@ShaunEvening
Copy link
Contributor Author

Hey @oliviervanbulck

Can you please share more information about the project?

Apologies for not being able to get it right for your project, I'm working on it 🙏
Please leave me the following details about your project:

Storybook version
@storybook/addon-styling version
Contents of your main.ts or main.js file
Contents of your preview.ts or preview.js file
The tool you wanted to auto-configure

@Crsk
Copy link

Crsk commented Jun 25, 2023

Error

=========================================

 🧰 Configuring @storybook/addon-styling

=========================================

/Users/User/Project/node_modules/@storybook/addon-styling/bin/postinstall.js:950
image
TypeError: Cannot read properties of undefined (reading 'tailwindcss')
    at zy (/Users/User/Project/node_modules/@storybook/addon-styling/bin/postinstall.js:950:43083)
    at EFr (/Users/User/Project/node_modules/@storybook/addon-styling/bin/postinstall.js:950:43456)
    at /Users/User/Project/node_modules/@storybook/addon-styling/bin/postinstall.js:1060:205
    at Array.find (<anonymous>)
    at wFr (/Users/User/Project/node_modules/@storybook/addon-styling/bin/postinstall.js:1060:183)
    at kFr (/Users/User/Project/node_modules/@storybook/addon-styling/bin/postinstall.js:1066:18)
    at Object.<anonymous> (/Users/User/Project/node_modules/@storybook/addon-styling/bin/postinstall.js:1069:1091)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)

Node.js v18.13.0

Storybook version
^7.0.23


@storybook/addon-styling version
^1.3.0


Content of main.ts

import type { StorybookConfig } from '@storybook/react-vite'
const config: StorybookConfig = {
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    '@storybook/addon-styling',
  ],
  framework: {
    name: '@storybook/react-vite',
    options: {},
  },
  docs: {
    autodocs: 'tag',
  },
}
export default config

Content of preview.ts

import type { Preview } from '@storybook/react'

const preview: Preview = {
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
  },
}

export default preview

The tool you wanted to auto-configure
Styled-components


build system: Lerna NX
bundler: Vite
compiler: SWC

@ShaunEvening
Copy link
Contributor Author

Hey @Crsk 👋

I just published 1.3.1 which should solve that error for you. Can you update and try again?

@ollebergkvist
Copy link

Does not seem to work with Astro

@ShaunEvening
Copy link
Contributor Author

Hi @ollebergkvist,

Astro is not currently supported by Storybook. This auto-configuration script is to configure styling in Storybook for tailwind, material UI, styled components, and Emotion

@forgo
Copy link

forgo commented Jul 11, 2023

When I run the codemod mentioned here, it has broken my project in ways I can't figure out how to revert.

At first I wasn't sure what the origin of the issue was, but as I stepped through creating a second Vite/React/TS/Storybook/TailwindCSS project from scratch, I got to this codemod again, and it produced the same error I had gotten stuck on previously.

After running the codemod, suddenly every story in the Storybook produces messages like this:

TypeError: Failed to fetch dynamically imported module: http://localhost:6006/node_modules/.cache/sb-vite/deps/@storybook_addon-essentials_outline_preview.js?v=556eddb9

For the record I was mostly following this guide, up until the point I needed to get TailwindCSS styles to apply.

I am trying to remove MUI from my dependencies in favor of Mantine, so not sure if this Tailwind doc should specify any concerns over running the codemod if MUI is not in the project.

I did notice it re-formatted and added a theme switcher to my .storybook/preview.tsx; however, I can't what what other files it may have touched.

Restarting the pnpm run storybook command yields a couple errors:

[1] ✘ [ERROR] The entry point "react" cannot be marked as external
[1]
[1] ✘ [ERROR] The entry point "react-dom" cannot be marked as external

Which is strange to me as I was seeing components render before running the codemod.

I have react, and react-dom in both peerDependencies and devDependencies.

and here is my vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import { resolve } from "path";
import dts from "vite-plugin-dts";
import tsConfigPaths from "vite-tsconfig-paths";
import * as packageJson from "./package.json";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), tsConfigPaths(), dts({ include: ["src"] })],
  build: {
    lib: {
      entry: resolve("src", "index.ts"),
      name: "vast-ui",
      formats: ["es", "cjs"],
      fileName: (format) => `vast-ui.${format === "cjs" ? "cjs" : "es.js"}`,
    },
    minify: true,
  },
  optimizeDeps: {
    exclude: Object.keys(packageJson.peerDependencies),
  },
});

The codemod says it's to configure Storybook with Tailwind, but it's not immediately clear that the script run via the following command is related to Tailwind at all:

# Run the postinstall script from the root of your project
node node_modules/@storybook/addon-styling/bin/postinstall.js

At the very least, there should be clarity in the doc stating there are two paths to take (auto or manual), and a note warning the user that the auto codemod approach could cause potential issues with the project, and should clearly state what the purpose of that script is and what files it changes.

I'm going to attempt running only down the "Manual" path after starting from scratch again to see if I can bypass this strange issue.

@ShaunEvening
Copy link
Contributor Author

Hey there, @forgo 👋

Woah! Looks like you've got a lot of moving parts to your problem here.

First of all, I'm sorry for all the hassle. I'm happy to help you figure this out but I need to know a few more things about your project first.

What version of Storybook are you using?
The tutorial you linked talked about using the beta of Storybook 7.0 but it's been out for a few months now and we're pretty close to releasing 7.1 in the coming weeks.

What version of @storybook/addon-styling are you using?
This is important to know so I can identify how far back this goes.

What styling library/libraries do you intend on using?
Your focus seems to be on getting Tailwind working but you're also mentioning MUI and Mantine which might change how we solve your issue.

Can you share the new repo you started from scratch with me so that I can debug it as well?
It's much easier for me to track down problems when I have an example codebase to work from.


Now, a little bit of clarification on the codemod script...

When I run the codemod mentioned here, it has broken my project in ways I can't figure out how to revert.

I'd strongly recommend that you run this codemod, or any other codemod for that matter on a clean branch without other changes. That way you can see the code diff and revert it if it's a problem.

However, this script only makes adjustments to two files. in your .storybook/main.ts file it will add the @storybook/addon-styling addon into the addons array. Then it will update .storybook/preview.ts to import the theme decorator and leave you some TODO comments to import your tailwind css file so that it can be injected into storybook.

At the very least, there should be clarity in the doc stating there are two paths to take (auto or manual), and a note warning the user that the auto codemod approach could cause potential issues with the project, and should clearly state what the purpose of that script is and what files it changes.

I can certainly do that. I thought that the two sections auto-migrate and manual would have been sufficient but i'm more than happy to adjust it if you have recommendations on how to better structure the document.

@unional
Copy link

unional commented Aug 4, 2023


node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: ENOENT: no such file or directory, open '.storybook/main.js'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '.storybook/main.js'
}
 ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL  Command failed with exit code 1: addon-styling-setup



Could't detect main.cjs (probably also main.mjs)

@ShaunEvening
Copy link
Contributor Author

Hey @unional, is it a hard requirement for you to use .cjs files? Storybook 7 anticipates .js or .ts for it's main and preview files

@unional
Copy link

unional commented Aug 4, 2023

It's not a hard requirement.
This is an older repo which was using .cjs and it has type: module in the package.json.

While it can be converted to ESM or TypeScript,
running the cli and fail would be confusing to the user.

@Chompas
Copy link

Chompas commented Aug 9, 2023

Hi, I'm trying to use the config without success. I have a monorepo with a Remix app (where I installed SB). When running the script I'm getting:

=========================================

 🧰 Configuring @storybook/addon-styling

=========================================

undefined:2
  name: getAbsolutePath('@storybook/react-vite'),
        ^

ReferenceError: getAbsolutePath is not defined
    at eval (eval at getFieldValue (/Users/emilianoviscarra/Projects/insights-platform/node_modules/@storybook/addon-styling/bin/postinstall.js:217:4641), <anonymous>:2:9)
    at eval (eval at getFieldValue (/Users/emilianoviscarra/Projects/insights-platform/node_modules/@storybook/addon-styling/bin/postinstall.js:217:4641), <anonymous>:4:4)
    at eval (<anonymous>)
    at yD.getFieldValue (/Users/emilianoviscarra/Projects/insights-platform/node_modules/@storybook/addon-styling/bin/postinstall.js:217:4641)
    at _D (/Users/emilianoviscarra/Projects/insights-platform/node_modules/@storybook/addon-styling/bin/postinstall.js:245:52007)
    at Wle (/Users/emilianoviscarra/Projects/insights-platform/node_modules/@storybook/addon-styling/bin/postinstall.js:245:52101)
    at OD (/Users/emilianoviscarra/Projects/insights-platform/node_modules/@storybook/addon-styling/bin/postinstall.js:245:52208)
    at dEe (/Users/emilianoviscarra/Projects/insights-platform/node_modules/@storybook/addon-styling/bin/postinstall.js:364:153)

Node.js v18.16.0
error Command failed with exit code 1.
  1. Storybook version: 7.2.2
  2. @storybook/addon-styling version: 1.3.6
  3. Contents of your main.ts or main.js file
import type { StorybookConfig } from '@storybook/react-vite'

import { join, dirname } from 'path'

/**
 * This function is used to resolve the absolute path of a package.
 * It is needed in projects that use Yarn PnP or are set up within a monorepo.
 */
function getAbsolutePath(value: string): any {
  return dirname(require.resolve(join(value, 'package.json')))
}
const config: StorybookConfig = {
  stories: ['../app/shared/components/**/*.mdx', '../app/shared/components/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  addons: [
    getAbsolutePath('@storybook/addon-links'),
    getAbsolutePath('@storybook/addon-essentials'),
    getAbsolutePath('@storybook/addon-onboarding'),
    getAbsolutePath('@storybook/addon-interactions'),
  ],
  framework: {
    name: getAbsolutePath('@storybook/react-vite'),
    options: {},
  },
  docs: {
    autodocs: 'tag',
  },
}
export default config
  1. Contents of your preview.ts or preview.js file
import type { Preview } from '@storybook/react'

const preview: Preview = {
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
  },
}

export default preview
  1. The tool you wanted to auto-configure: Tailwind

@ShaunEvening
Copy link
Contributor Author

Hey @Chompas 👋

Sorry about the trouble there, the codemod doesn't account for a function call like getAbsolutePath to be in your addons array. I'll have to think about how I can improve on that for the future.

However, I have some good news for you. Since you're using vite, tailwind should already work for your storybook project. just import your global css file into your .stortybook/preview.ts file

@lianer3588
Copy link

lianer3588 commented Aug 21, 2023

Hello, I encountered the same error, but I used webpack5.

undefined:2
name: getAbsolutePath('@storybook/react-webpack5'),
^

ReferenceError: getAbsolutePath is not defined

@Chompas
Copy link

Chompas commented Aug 21, 2023

However, I have some good news for you. Since you're using vite, tailwind should already work for your storybook project. just import your global css file into your .stortybook/preview.ts file

Yes. this is exactly what I did and got it running. Thanks.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests