storybookjs / storybook

Storybook is the industry standard workshop for building, documenting, and testing UI components in isolation
https://storybook.js.org
MIT License
84.03k stars 9.24k forks source link

[Bug]: Fails to start using Vite v4.3 (esbuild error) #22253

Closed GRA0007 closed 1 year ago

GRA0007 commented 1 year ago

Describe the bug

With the latest Vite update (v4.3.1), Storybook (using v7.0.7) fails to build with the following error at the top of the logs:

[ERROR] Could not read from file: /path/to/node_modules/.cache/vite-plugin-externals/@storybook/core-events.js

Then after this there are lots of the following for many packages:

✘ [ERROR] Invalid command: on-resolve [plugin JavaScript plugins]

    node_modules/vite/node_modules/esbuild/lib/main.js:745:12:
      745 │       handleRequest(packet.id, packet.value);
          ╵             ^

    at handleRequest (/path/to/node_modules/vite/node_modules/esbuild/lib/main.js:745:13)
    at handleIncomingPacket (/path/to/node_modules/vite/node_modules/esbuild/lib/main.js:762:7)
    at Socket.readFromStdout (/path/to/node_modules/vite/node_modules/esbuild/lib/main.js:690:7)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readable:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)

  The plugin "JavaScript plugins" was triggered by this import

    node_modules/@storybook/blocks/dist/index.mjs:81:2422:
      81 │ ...mposeConfigs}from"@storybook/preview-api";import{Channel}from"@storybook/channels";import{DocsContext as DocsContext2}from"@storybook/preview-...

Before updating to Vite v4.3.1 there were no issues with starting Storybook, and none of the config files have changed.

To Reproduce

No response

System

Environment Info:

  System:
    OS: macOS 13.2.1
    CPU: (8) arm64 Apple M1
  Binaries:
    Node: 18.6.0 - /var/folders/vr/yrskg7qd5fbcj2kyy_8q52jc0000gn/T/yarn--1682465109348-0.43062969347345303/node
    Yarn: 1.22.19 - /var/folders/vr/yrskg7qd5fbcj2kyy_8q52jc0000gn/T/yarn--1682465109348-0.43062969347345303/yarn
    npm: 9.6.0 - ~/Library/Caches/fnm_multishells/91857_1682415868456/bin/npm
  Browsers:
    Chrome: 112.0.5615.137
    Safari: 16.3
  npmPackages:
    @storybook/addon-a11y: ^7.0.7 => 7.0.7 
    @storybook/addon-essentials: ^7.0.7 => 7.0.7 
    @storybook/addon-interactions: ^7.0.7 => 7.0.7 
    @storybook/addon-links: ^7.0.7 => 7.0.7 
    @storybook/react: ^7.0.7 => 7.0.7 
    @storybook/react-vite: ^7.0.7 => 7.0.7

Additional context

No response

Flamenco commented 1 year ago

@GerroDen Yes we are experiencing the same issue still, and have reverted back to vite 4.2.3.

jfairley commented 1 year ago

I don't know whether this is related, but I had to boot a couple plugins to make my storybook work.

in .storybook/main.ts:

  viteFinal: (config) =>
    mergeConfig(
      Object.assign({}, config, {
        plugins: config.plugins?.filter((plugin) => !["vite:dts", "vite-plugin-checker"].includes(plugin?.["name"])),
      }),
      {
        server: {
          watch: {
            ignored: ["**/.env.test", "**/coverage/**"],
          },
        },
      },
    ),

IIRC...

Another tweak I have (unrelated to storybook) is in vite.config.ts.

  plugins: [
    // ...
    mode === "production" && process.env.CYPRESS !== "true" && checker({ typescript: true }),
  ]

The lesson is just comment out your plugins one at a time and see if you make progress. YMMV

woodreamz commented 1 year ago

@jfairley Thanks for the tips, I noticed the server was restarting on .env changes:

image

By adding this in ./storybook/main.ts, it seems to fix the issue (at least for now):

viteFinal: async (config) => {
    return mergeConfig(config, {
      server: {
        watch: {
          ignored: ['**/.env.*', '**/coverage/**'],
        },
      },
    });
  },
IanVS commented 1 year ago

I also notice my server restarting on .env changes, but they happen when no changes to the file are actually made. Is that what you experience as well? Or are you actually changing the contents of the file?

That's a good idea to ignore files that are causing problems, but keep in mind that you'll need to manually restart if you do change a .env file, of course.

jfairley commented 1 year ago

@IanVS Ah yes, definitely, I should've mentioned that too. My storybook was also looping due to supposed changes to my .env files, though I had not changed them at all. That is why I added the server.watch.ignored section.

Edit: I have the **/coverage/** part because I'm using @storybook/test-runner, and writes to coverage also cause restarts.

woodreamz commented 1 year ago

@IanVS I don't change anything in the file, I don't know why it detects a change. The message appears on start.

GerroDen commented 1 year ago

Vite logs, it detects updates on tsconfig.json multiple times and in the case of that error with every error message.

jrozbicki commented 1 year ago

@woodreamz ignoring .env is a brilliant workaround. Vite doesn't restart in a loop anymore, was able run vite@4.4.9 (latest atm) and storybook@7.2.2 (latest atm)

Full .storybook/main.ts below:

import path from "path";

import type { StorybookConfig } from "@storybook/react-vite";
import { mergeConfig } from "vite";

const getAbsolutePath = (packageName: string) =>
  path.dirname(require.resolve(path.join(packageName, 'package.json')));

const config: StorybookConfig = {
  stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"],
  addons: [
    getAbsolutePath("@storybook/addon-links"),
    getAbsolutePath("@storybook/addon-essentials"),
    getAbsolutePath("@storybook/addon-onboarding"),
    getAbsolutePath("@storybook/addon-interactions"),
    getAbsolutePath("@storybook/addon-styling"),
  ],
  framework: {
    name: getAbsolutePath("@storybook/react-vite") as "@storybook/react-vite",
    options: {},
  },
  docs: {
    autodocs: "tag",
  },
  viteFinal: async (config) => {
    return mergeConfig(config, {
      server: {
        watch: {
          // otherwise Vite for some reason detects changes in .env.* files and ends up in restart loop 
          ignored: ['**/.env.*'],
        },
      },
    });
  },
};

export default config;
GerroDen commented 1 year ago

Thanks, the ignoring helps in my case for the viteFinal config in the main.ts:

        server: {
          watch: {
            // somehow vite in storybook keeps on detecting changes in these files without edits
            // see: https://github.com/storybookjs/storybook/issues/22253
            ignored: ["**/.env", "**/.env.local", "**/tsconfig.json", "**/tsconfig.node.json"],
          },
        },

Another fun fact to me is, that with every browser reload, vite detects new plugins to optimize:

10:27:58 AM [vite] ✨ new dependencies optimized: @storybook/addon-styling, @storybook/theming
10:27:58 AM [vite] ✨ optimized dependencies changed. reloading
10:28:42 AM [vite] ✨ new dependencies optimized: @storybook/addon-docs/mdx-react-shim
10:28:42 AM [vite] ✨ optimized dependencies changed. reloading

Both updates appeared after a reload in the browser!

ryota-murakami commented 1 year ago

I also facing rapid .env file changing, but this is solved after migrate yarn v1 to pnpm in my case.
There is no special settings. Almost default setup by npx storybook@latest init.

main.ts

import type { StorybookConfig } from '@storybook/react-vite'

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

preview.tsx

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

import { initialize, mswDecorator } from 'msw-storybook-addon'

import { Provider as ReduxStoreProvider } from 'react-redux'
import { store } from '../src/redux/store'
import { handlers } from '../mocks/handlers'
import '../src/index.css'

// Initialize MSW
initialize()

const preview: Preview = {
  parameters: {
    msw: { handlers: [...handlers] },
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
  },
  decorators: [
    mswDecorator,
    (Story) => (
      <ReduxStoreProvider store={store}>
        <Story />
      </ReduxStoreProvider>
    ),
  ],
}

export default preview

package.json

{
  "name": "nsx",
  "private": "true",
  "version": "0.0.1",
  "license": "MIT",
  "author": "Ryota Murakami",
  "homepage": "https://github.com/laststance/nsx",
  "msw": {
    "workerDirectory": "public"
  },
  "volta": {
    "node": "18.17.1"
  },
  "dependencies": {
    "@headlessui/react": "^1.7.16",
    "@heroicons/react": "^2.0.18",
    "@hookform/resolvers": "^3.2.0",
    "@reduxjs/toolkit": "2.0.0-alpha.6",
    "@sentry/react": "^7.63.0",
    "@sentry/tracing": "^7.63.0",
    "bcrypt": "^5.1.0",
    "body-parser": "^1.20.2",
    "chalk": "^4.1.2",
    "clsx": "^2.0.0",
    "compression": "^1.7.4",
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "cron": "^2.4.0",
    "express": "^4.18.2",
    "express-oas-generator": "^1.0.46",
    "history": "^5.3.0",
    "jsonwebtoken": "^9.0.1",
    "morgan": "^1.10.0",
    "mysql2": "^3.6.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-ga4": "^2.1.0",
    "react-helmet": "^6.1.0",
    "react-hook-form": "^7.45.4",
    "react-markdown": "^8.0.7",
    "react-redux": "^8.1.2",
    "react-router-dom": "^6.15.0",
    "react-spinners": "^0.13.8",
    "redux": "5.0.0-alpha.6",
    "redux-first-history": "^5.1.1",
    "redux-persist": "^6.0.0",
    "rehype-raw": "^6.1.1",
    "remark-breaks": "^3.0.3",
    "remark-gfm": "^3.0.1",
    "sequelize": "^6.32.1",
    "superstruct": "^1.0.3",
    "web-vitals": "^3.4.0"
  },
  "devDependencies": {
    "@faker-js/faker": "^8.0.2",
    "@hookform/devtools": "^4.3.1",
    "@redocly/cli": "^1.0.2",
    "@storybook/addon-essentials": "^7.2.2",
    "@storybook/addon-interactions": "^7.2.2",
    "@storybook/addon-links": "^7.2.2",
    "@storybook/addon-mdx-gfm": "^7.2.2",
    "@storybook/addon-onboarding": "^1.0.8",
    "@storybook/blocks": "^7.2.2",
    "@storybook/react": "^7.2.2",
    "@storybook/react-vite": "^7.2.2",
    "@storybook/testing-library": "^0.2.0",
    "@tailwindcss/aspect-ratio": "^0.4.2",
    "@tailwindcss/forms": "^0.5.4",
    "@tailwindcss/line-clamp": "^0.4.4",
    "@tailwindcss/typography": "^0.5.9",
    "@testing-library/dom": "^9.3.1",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^14.0.0",
    "@testing-library/user-event": "^14.4.3",
    "@types/assert": "^1.5.6",
    "@types/bcrypt": "^5.0.0",
    "@types/body-parser": "^1.19.2",
    "@types/compression": "^1.7.2",
    "@types/cookie-parser": "^1.4.3",
    "@types/cors": "^2.8.13",
    "@types/express": "^4.17.17",
    "@types/jsonwebtoken": "^9.0.2",
    "@types/morgan": "^1.9.4",
    "@types/node": "^20.4.9",
    "@types/react": "^18.2.20",
    "@types/react-dom": "^18.2.7",
    "@types/react-helmet": "^6.1.6",
    "@types/react-syntax-highlighter": "^15.5.7",
    "@types/testing-library__jest-dom": "^5.14.9",
    "@typescript-eslint/eslint-plugin": "^6.3.0",
    "@typescript-eslint/parser": "^6.3.0",
    "@vitejs/plugin-react-swc": "^3.3.2",
    "@vitest/ui": "^0.34.1",
    "all-contributors-cli": "^6.26.1",
    "autoprefixer": "^10.4.14",
    "concurrently": "^8.2.0",
    "cross-env": "^7.0.3",
    "cypress": "^12.17.3",
    "cypress-slow-down": "^1.2.1",
    "dotenv": "^16.3.1",
    "dotenv-cli": "^7.2.1",
    "eslint": "^8.46.0",
    "eslint-config-ts-prefixer": "^0.22.0",
    "eslint-import-resolver-typescript": "^3.6.0",
    "eslint-plugin-cypress": "^2.14.0",
    "eslint-plugin-import": "^2.28.0",
    "eslint-plugin-jsx-a11y": "^6.7.1",
    "eslint-plugin-prettier": "^5.0.0",
    "eslint-plugin-react": "^7.33.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-sort-keys-fix": "^1.1.2",
    "eslint-plugin-storybook": "^0.6.13",
    "jsdom": "^22.1.0",
    "msw": "^1.2.3",
    "msw-storybook-addon": "^1.8.0",
    "node-fetch": "^3.3.2",
    "nodemon": "^3.0.1",
    "postcss": "^8.4.27",
    "prettier": "^3.0.1",
    "prettier-plugin-tailwindcss": "^0.5.1",
    "rimraf": "^5.0.1",
    "sequelize-cli": "^6.6.1",
    "serve": "^14.2.0",
    "storybook": "^7.2.2",
    "tailwindcss": "^3.3.3",
    "ts-node": "^10.9.1",
    "ts-node-dev": "^2.0.0",
    "typescript": "^5.1.6",
    "vite": "^4.4.9",
    "vite-plugin-environment": "^1.1.3",
    "vitest": "^0.34.1",
    "vitest-matchmedia-mock": "^1.0.2"
  },
  "scripts": {
    "start": "vite",
    "dev": "vite",
    "build": "dotenv -e .env.prod vite build",
    "preview": "vite preview",
    "serve": "serve build",
    "test": "dotenv -e .env.test -- vitest",
    "lint": "eslint . --ext .ts,.tsx,.js,jsx --report-unused-disable-directives",
    "lint:fix": "eslint . --ext .ts,.tsx,.js,jsx --fix --report-unused-disable-directives",
    "typecheck": "tsc --noEmit",
    "clean": "rimraf yarn.lock node_modules build server_build storybook-static",
    "prettier": "prettier --write \"**/*.+(js|ts|tsx|json|yml|css|md|mdx)\"",
    "storybook": "dotenv -e .env.storybook -- storybook dev -p 6006",
    "build-storybook": "dotenv -e .env.storybook -- storybook build",
    "serve:storybook": "serve storybook-static",
    "server:start": "cross-env NODE_ENV=development nodemon --ext ts,js --watch 'server/index.ts' --ignore './src' --exec ts-node --files --project server/tsconfig.json server/index.ts",
    "server:build": "tsc -p server/tsconfig.json && cp -r server/db/migrations server_build && cp server/db/config.json server_build/server/db/config.json",
    "deploy": "bash scripts/deploy",
    "workflow:deploy": "yarn build && yarn server:build && yarn deploy",
    "validate": "./scripts/validate",
    "openapi": "redocly preview-docs openapi_v3.json",
    "db:hashgen": "node server/db/scripts/passhashgen.js",
    "db:reset": "yarn db:drop && yarn db:create && yarn db:migrate && yarn db:seed:all",
    "db:truncate": "yarn db:drop && yarn db:create && yarn db:migrate",
    "db:create": "sequelize db:create",
    "db:drop": "sequelize db:drop",
    "db:migrate": "sequelize db:migrate",
    "db:seed": "sequelize db:seed",
    "db:seed:undo": "sequelize db:seed:undo",
    "db:seed:all": "sequelize db:seed:all",
    "db:seed:undo:all": "sequelize db:seed:undo:all",
    "cy:open": "cypress open",
    "e2e:admin": "cypress run --headed --spec cypress/e2e/admin_basic.cy.js",
    "e2e:admin:headless": "cypress run --spec cypress/e2e/admin_basic.cy.js",
    "e2e:visitor": "cypress run --headed --spec cypress/e2e/visitor_basic.cy.js",
    "e2e:visitor:headless": "cypress run --spec cypress/e2e/visitor_basic.cy.js",
    "e2e:new-install-user": "cypress run --headed --spec cypress/e2e/new_isntalled_user_flow.cy.js",
    "e2e:admin:firefox": "cypress run --headed -b firefox --spec cypress/e2e/admin_basic.cy.js",
    "e2e:visitor:firefox": "cypress run --headed -b firefox --spec cypress/e2e/visitor_basic.cy.js"
  }
}
mihhauk commented 1 year ago
image

By adding this in ./storybook/main.ts, it seems to fix the issue (at least for now):

viteFinal: async (config) => {
    return mergeConfig(config, {
      server: {
        watch: {
          ignored: ['**/.env.*','],
        },
      },
    });
  },

Thanks all! I have also managed to fix the issue by ignoring the .env files as described above.

An additional piece of information I've gathered is that this behavior was actually caused by the addon @storybook/addon-essentials. When I removed it from the config loading issue disappeared even without ignoring the .env files.

eifr-vault commented 1 year ago

image ignoring env did fix some of the issues but I'm still getting this ^

vite.config:

import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import macrosPlugin from 'vite-plugin-babel-macros';
import svgrPlugin from 'vite-plugin-svgr';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig(() => {
  return {
    plugins: [
      react(
        process.env.CYPRESS === 'true'
          ? { babel: { plugins: ['istanbul'] } }
          : undefined
      ),
      tsconfigPaths(),
      svgrPlugin({ svgrOptions: { icon: true } }),
      macrosPlugin(),
    ],
    build: {
      sourcemap: true,
      outDir: 'dist',
    },
    server: {
      port: 8080,
      strictPort: true,
      host: 'eifr.test',
    },
    optimizeDeps: {
      include: ['@material-ui/pickers', 'd3'],
    },
  };
});
GerroDen commented 1 year ago

@eifr-vault did you also try to ignore any tsconfig.json? That helped me.

eifr-vault commented 1 year ago

@eifr-vault did you also try to ignore any tsconfig.json? That helped me.

i don't know how I missed the previous comments lol WORKS! thx 🙏

TNAJanssen commented 1 year ago

Same issue here, but then not with the storybooks. I'm using NX however, and it keeps restarting due to file changes that really did not happen.

When downgrading to Vite 4.1.4 it indeed seems solved. However it does really suck, and should be an issue

segevfiner commented 1 year ago

Tried to debug it a little in some setup I have and it looks to me like this is the cause: https://github.com/paulmillr/chokidar/issues/1286

GerroDen commented 1 year ago

@segevfiner oh so it's a Mac issue. I'm using Mac. 💡

Flamenco commented 1 year ago

Confirming that manually patching fsevents fixes this issue on Mac

https://github.com/fsevents/fsevents/commit/63709df0fd91549050e2e3f38b1695f49f6387a8

function getFileType(flags) {
  if (events.ItemIsFile & flags) return "file";
  if (events.ItemIsDir & flags) return "directory";
  if (events.MustScanSubDirs & flags) return "directory";  // <--- add this line
  if (events.ItemIsSymlink & flags) return "symlink";
}
IanVS commented 1 year ago

Good news! fsevents@2.3.3 has been released with the fix. Depending on your package manager, you should be able to <pkgmgr> up fsvents (though watch out for pnpm, it may update other unrelated packages: https://github.com/pnpm/pnpm/issues/6657).

I'll close this out now, but please let us know if you continue to have issues with this.

danielvinter commented 1 year ago

npm up fsevents worked for me

subharb commented 11 months ago

Deleting node_modules and reinstalling it with yarn solve it.