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

[Bug]: 7.6.5 @storybook/react-vite runs fine in dev but builds have JavaScript error that blocks loading #25247

Open
nstuyvesant opened this issue Dec 15, 2023 · 13 comments

Comments

@nstuyvesant
Copy link

nstuyvesant commented Dec 15, 2023

Describe the bug

Working on a revision to @carbon/charts-react to use @storybook/react-vite instead of @storybook/react (Webpack).

When I run npx storybook dev -p 9006, the Storybook runs and behaves as expected. When I do a build of the Storybook npx storybook build -o demo/bundle then run that either using a local web server or push it to Vercel, I get a JavaScript console error...

Uncaught ReferenceError: dc is not defined
for this line...

dc.__docgenInfo = {
	description: '',
	methods: [
		{ name: 'addLineEventListener', docblock: null, modifiers: [], params: [], returns: null },
		{ name: 'addNodeEventListener', docblock: null, modifiers: [], params: [], returns: null },
		{
			name: 'traverse',
			docblock: null,
			modifiers: [],
			params: [
				{ name: 'e', optional: !1, type: null },
				{ name: 't', optional: !1, type: null },
				{ name: 's', optional: !0, type: null }
			],
			returns: null
		},
		{ name: 'getRightArrowIcon', docblock: null, modifiers: [], params: [], returns: null },
		{ name: 'destroy', docblock: null, modifiers: [], params: [], returns: null }
	],
	displayName: 'dc'
}

Here is my .storybook/main.ts for the @carbon/charts-react package...

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

const config: StorybookConfig = {
	stories: ['../src/stories/**/*.stories.tsx', '../src/stories/**/*.mdx'],
	staticDirs: ['../../core/.storybook/assets'],

	addons: [
		{
			name: '@storybook/addon-essentials',
			options: {
				actions: false
			}
		}
	],

	framework: {
		name: '@storybook/react-vite',
		options: {}
	},

	docs: {
		autodocs: 'tag'
	},

	// typescript: {
	// 	reactDocgen: 'react-docgen'
	// },

	async viteFinal(config: InlineConfig) {
		config.plugins = config.plugins!.filter((plugin) => plugin!.name !== 'vite:dts')
		const newConfig: InlineConfig = mergeConfig(config, {
			build: {
				chunkSizeWarningLimit: 1800,
			},
			optimizeDeps: {
				include: [
					'@carbon/charts'
				]
			}
		})
		// console.log('Vite Config', newConfig)
		return newConfig
	},

	features: {
		storyStoreV7: false // required for storiesOf API
	}
}
export default config

CLUES:

  1. If I comment out the optimizeDeps.include for @carbon/charts, I get the SAME error when I run the dev server.
  2. Other packages do not have the problem - @carbon/charts uses @storybook/html-vite, @carbon/charts-svelte uses @storybook/sveltekit, @carbon/charts-vue uses @storybook/vue3-vite. These component libraries are thin wrappers around @carbon/charts
  3. Using @storybook/react (Webpack) works but the goal is to get rid of Webpack.

To Reproduce

Cannot reproduce with a minimal repro but the steps to reproduce are not complicated...

  1. Install the monorepo
git clone https://github.com/nstuyvesant/carbon-charts.git
cd carbon-charts
yarn install
yarn build
cd packages/react
  1. Edit packages/react/.storybook/main.ts and comment out these lines
	typescript: {
		reactDocgen: false // Required to overcome https://github.com/storybookjs/storybook/issues/25247
	},
  1. Run yarn storybook to see it working at http://localhost:9006
  2. Stop the dev server
  3. Run yarn build:demo
  4. Using a local web server, host demo/bundle with index.html as the default doc then access it via http://localhost. Storybook will not fully load and the error mentioned above will be logged to the JavaScript Console.

System

Storybook Environment Info:

  System:
    OS: macOS 14.2
    CPU: (10) arm64 Apple M1 Pro
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.19.0 - /opt/homebrew/bin/node
    Yarn: 4.0.2 - /opt/homebrew/bin/yarn <----- active
    npm: 10.2.5 - /opt/homebrew/bin/npm
  Browsers:
    Chrome: 120.0.6099.109
    Safari: 17.2

  Other important environmental info:
    Monorepo: Yes
    Storybook: 7.6.5
    Lerna (nx): 8.0.1
    Vite: 5.0.10
    TypeScript: 5.3.3
    React: 18.2.0

Additional context

Our .storybook/main.ts must have features.storyStoreV7 set to false because we have almost 1,000 stories generated via the storiesOf() API.

Other things I tried without success...

  1. Setting typescript.reactDocgen to 'react-docgen' without success.
  2. Setting build.rollupOptions.treeshake = false to the config in viteFinal().
  3. Reverting to Vite 4
@nstuyvesant
Copy link
Author

Just got a workaround...

	typescript: {
		reactDocgen: false
	},

I'm not clear what I've lost in the process as the generated build appears to do everything it used to do when I used the Webpack version.

@nstuyvesant
Copy link
Author

This is the updated packages/react/.storybook/main.ts...

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

const config: StorybookConfig = {
	stories: ['../src/stories/**/*.stories.tsx', '../src/stories/**/*.mdx'],
	staticDirs: ['../../core/.storybook/assets'],
	framework: {
		name: '@storybook/react-vite',
		options: {}
	},
	addons: [
		{
			name: '@storybook/addon-essentials',
			options: {
				actions: false
			}
		}
	],
	core: {
    disableTelemetry: true
  },
	docs: {
		autodocs: false
	},
	typescript: {
		reactDocgen: false // Required to overcome https://github.com/storybookjs/storybook/issues/25247
	},
	async viteFinal(config: InlineConfig) {
		config.plugins = config.plugins!.filter((plugin) => plugin!.name !== 'vite:dts')
		const newConfig: InlineConfig = mergeConfig(config, {
			build: {
				chunkSizeWarningLimit: 1800,
				// rollupOptions: {
					// Avoid error Failed to load url /sb-preview/runtime.js (resolved id: /sb-preview/runtime.js). Does the file exist?
          // external: [
					// 	/\/sb-preview\/runtime.js$/ // does not prevent error
          // ]
        // }
			},
			optimizeDeps: {
				include: [
					'@carbon/charts'
				],
				exclude: ['@carbon/telemetry']
			}
		})
		return newConfig
	},
	features: {
		storyStoreV7: false // required for storiesOf API
	}
}
export default config

I still get the error...

11:01:11 AM [vite] Pre-transform error: Failed to load url /sb-preview/runtime.js (resolved id: /sb-preview/runtime.js). Does the file exist?

But it doesn't block anything.

@Kisama
Copy link

Kisama commented Dec 22, 2023

I have same issue, run storybook is ok, but 'storybook build` can make console error

Uncaught (in promise) ReferenceError: Cannot access 'Ya' before initialization
    at index-QmdEasgT.js:159:8825
    at async Promise.all (:63342/ujet-agent-desktop/storybook-static/index 1)
preview-PqG2-CBx.js:1 Uncaught (in promise) TypeError: e is not a constructor
    at Object.renderer (preview-PqG2-CBx.js:1:324)
    at async MdxDocsRender.renderToElement (runtime.js:92:3625)
import { StorybookConfig } from '@storybook/types';

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

@nstuyvesant
Copy link
Author

@Kisama - what happens if you set docs.autodocs to false?

@Kisama
Copy link

Kisama commented Dec 27, 2023

@nstuyvesant same result, tsx storybooks are OK but the all of mdx storybooks return same console error

@nstuyvesant
Copy link
Author

@Kisama - Your error seems a bit different from mine. My issue prevented the TSX storybooks from working and it was related to typescript.reactDocgen.

@PilotConway
Copy link

I am running into this same issue, but it happens both storybook dev and build. We have a monorepo with multiple UI packages that depend on a common package and any of the storybooks that rely on the common UI package throws the same reference error. The base package works without issue.

The workaround of setting reactDocgen: false does work, but obviously that's not a long term solution as we lose a lot with that.

This was not an issue when our common UI package was in it's own repo that published an npm package, but we are moving that package into the monorepo and that's triggering this. (using the yarn 3 monorepo linking using dependencies: { "myPackage": "workspace:^" }.

@nstuyvesant
Copy link
Author

@PilotConway - in our viteFinal() in .storybook/main.ts, adding optimizeDeps.include for common package helped when running the Storybook in dev (still had the build problems). Curious if this would exhibit the same behavior for you.

@PilotConway
Copy link

@nstuyvesant I did try that as well (in both main.js and in my main vite config) but that didn't fix it. I was investigating more yesterday and it seems like tree shaking isn't the culprit, which would explain why optimizeDeps wouldn't do anything.

The index.js where the docgen is being added imports everything as defaultX then re-exports them with the proper named exports. So the actual component name is never used in the scope of the file itself.

This is our source index file:

export * from "./components"

And the vite/rollup output of that file is:

import { default as default9 } from "./components/MyComponent";

export { default9 as MyComponent }

So when docgen adds the reference for MyComponent at the bottom of that file, MyComponent isn't in scope.

@isaacrankinactionstep
Copy link

isaacrankinactionstep commented Jan 11, 2024

I have the same issue after switching from using Webpack to Vite with Storybook.

MicrosoftTeams-image

Given the following JavaScript:

// index.js
import DevContainer from './DevContainer';

export default DevContainer;

It produces this, where you can see the "Dev" is not in scope here.

import DevContainer from "/@fs/home/isaacrankin/Projects/.../src/modules/oauth/components/dev/DevContainer.jsx?t=1705010022953";

export default DevContainer;
;Dev.__docgenInfo = {
    "description": "",
    "methods": [],
    "displayName": "Dev"
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIiJdLCJzb3VyY2VzQ29udGVudCI6W10sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTsifQ==

One workaround seems to be to rename the imports to "Dev", like this:

import Dev from './DevContainer';

export default Dev;

@nstuyvesant
Copy link
Author

We have Storybook for several of the packages in our monorepo. Four use Vite with Storybook. Only the one based on React has this issue.

@PilotConway
Copy link

I had gotten this working doing something similar forcing named exports and default exports in our files, but it just started popping up again. Digging in, I realize that turning off minification in vite solves it for us. That keeps the named imports in place so they are still in scope when react-docgen adds that snippet of code.

We ended up setting minify to false when mode === "development" and always running vite with the mode --mode=development flag when we are building or running storybook and that gets around the issue for us, and we can still minify for prod builds.

@hiren3897
Copy link

hiren3897 commented May 3, 2024

I have a similar issue. When I run the storybook locally in development, it works fine, but when I build the storybook, the 'Docs' are not rendered and throw some strange error in the console.

Below is my issue.
#26944

My Vite Config

/* eslint-disable import/no-extraneous-dependencies */
import react from "@vitejs/plugin-react-swc";
import { defineConfig } from "vite";
import checker from "vite-plugin-checker";
import istanbul from "vite-plugin-istanbul";
import svgr from "vite-plugin-svgr";
import topLevelAwait from "vite-plugin-top-level-await";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [
    tsconfigPaths(),
    svgr(),
    react(),
    checker({
      typescript: true,
    }),
    topLevelAwait(),
    istanbul({
      cypress: true,
      requireEnv: false,
    }),
  ],
  mode: "development",
  server: {
    port: 3000,
  },
  resolve: {
    alias: {
      "@cornerstonejs/tools": "@cornerstonejs/tools/dist/umd/index.js",
    },
  },
  build: {
    outDir: "build",
    minify: false,
    rollupOptions: {
      output: {
        manualChunks: {
          "cornerstone-core": ["@cornerstonejs/core"],
          "cornerstonejs-dicom-image-loader": ["@cornerstonejs/dicom-image-loader"],
        },
      },
    },
  },
});

My .storybook/main.ts

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

const config: StorybookConfig = {
  stories: ["../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@chromatic-com/storybook",
    "@storybook/addon-interactions",
  ],
  typescript: {
    reactDocgen: false
  },
  env: (config) => ({
    ...config,
    NODE_ENV: 'development',
  }),
  core: {
    builder: "@storybook/builder-vite",
  },
  framework: {
    name: "@storybook/react-vite",
    options: {},
  },
  docs: {
    autodocs: "tag",
    defaultName: 'Documentation',
  },
};
export default config;
{
  "scripts": {
    "start:dev": "VITE_API_URL=https://dev.graphql.milvue.com vite",
    "start:local": "VITE_API_URL=http://localhost:8000 vite",
    "build": "tsc && vite build",
    "test": "jest",
    "jest:coverage": "pnpm run test --ci",
    "preview": "vite preview",
    "lint": "eslint .",
    "storybook": "storybook dev -p 6006",
    "build-storybook": "NODE_OPTIONS=--max_old_space_size=4096 NODE_ENV=development storybook build",
    "cypress:open": "cypress open",
    "cypress:test": "cypress run --component",
    "cypress:verify": "cypress verify"
  }

  }

@PilotConway

I had gotten this working doing something similar forcing named exports and default exports in our files, but it just started popping up again. Digging in, I realize that turning off minification in vite solves it for us. That keeps the named imports in place so they are still in scope when react-docgen adds that snippet of code.

We ended up setting minify to false when mode === "development" and always running vite with the mode --mode=development flag when we are building or running storybook and that gets around the issue for us, and we can still minify for prod builds.

I tired your solution for building the storybook but have same error

runtime.js:121 Uncaught (in promise) ReferenceError: Cannot access 'Mo' before initialization
    at DocsRenderer-K4EAMTC…11396af.js:159:8822
renderToElement	@	runtime.js:121
await in renderToElement (async)		
renderSelection	@	runtime.js:121
await in renderSelection (async)		
onSetCurrentStory	@	runtime.js:121
await in onSetCurrentStory (async)		
(anonymous)	@	runtime.js:7
handleEvent	@	runtime.js:7
(anonymous)	@	runtime.js:7
handler	@	runtime.js:7
handleEvent	@	runtime.js:7
postMessage (async)		
(anonymous)	@	chunk-RHK3WMPG.js:16
send	@	chunk-RHK3WMPG.js:16
(anonymous)	@	chunk-RHK3WMPG.js:16
handler	@	chunk-RHK3WMPG.js:16
emit	@	chunk-RHK3WMPG.js:16
emit	@	chunk-RHK3WMPG.js:21
(anonymous)	@	chunk-O6NCVXC4.js:177
commitHookEffectListMount	@	chunk-UOBNU442.js:98
commitPassiveMountOnFiber	@	chunk-UOBNU442.js:111
commitPassiveMountEffects_complete	@	chunk-UOBNU442.js:111
commitPassiveMountEffects_begin	@	chunk-UOBNU442.js:111
commitPassiveMountEffects	@	chunk-UOBNU442.js:111
flushPassiveEffectsImpl	@	chunk-UOBNU442.js:111
flushPassiveEffects	@	chunk-UOBNU442.js:111
commitRootImpl	@	chunk-UOBNU442.js:111
commitRoot	@	chunk-UOBNU442.js:111
performSyncWorkOnRoot	@	chunk-UOBNU442.js:111
flushSyncCallbacks	@	chunk-UOBNU442.js:32
(anonymous)	@	chunk-UOBNU442.js:111
```

Can you help me to resolve this problem ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Needs Discussion
Development

No branches or pull requests

6 participants