Closed stephenkoo closed 1 year ago
@stephenkoo don't know if this will fix your problem, but the custom webpack config with webpackFinal
is probably conflicting with preset-typescript
, which is doing mostly the same thing (but using ts-loader
). that certainly can't be helping things.
Thanks, @shilman. Would you recommend keeping the TS preset here and removing the webpackFinal
section?
{
name: '@storybook/preset-typescript',
options: {
tsLoaderOptions: {
configFile: path.resolve(__dirname, '../tsconfig.json'),
},
tsDocgenLoaderOptions: {
tsconfigPath: path.resolve(__dirname, '../tsconfig.json'),
},
forkTsCheckerWebpackPluginOptions: {
colors: false, // disables built-in colors in logger messages
},
include: [path.resolve(__dirname, '../src')],
},
Yeah, using presets is always recommended unless you need more configurability.
Thanks. The preset (or webpackFinal
) doesn't seem to handle React elements in preview.tsx
- I'm unable to import GlobalStyles using the method here:
(Viewable on https://github.com/stephenkoo/aesther/compare/sk/feat-add-storybook):
import React from 'react'
import { addDecorator } from '@storybook/react'
import { GlobalStyle } from '../src/styles/global'
addDecorator(story => (
<>
<GlobalStyle />
{story()}
</>
))
because:
Module parse failed: Unexpected token (11:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| addDecorator(withA11y)
| addDecorator(story => (
> <>
| <GlobalStyle />
| {story()}
@ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/preview.tsx ./.storybook/generated-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=true main[2]
What's the right way to configure Storybook's preset to enable this?
@stephenkoo Nobody transpiles your JSX. NextJS needs your tsconfig to have jsx: preserve, Storybook Preset TS needs jsx: react
You can create new tsconfig.json in .storybook dir, extend the main one and override compilerOptions.jsx.
{
"extends": "../tsconfig.json",
"compilerOptions": {
"jsx": "react"
}
}
Thanks @hasparus for taking a look! I did as suggested but the "missing appropriate loader" error still seems to occur when running yarn storybook
. :(
Could you try pointing Storybook to the new tsconfig.json?
Instead of ../tsconfig.json it will be ./tsconfig.json.
Next uses Babel (preset next) so it won’t be exactly the same setup, but it might be enough for simple cases.
@hasparus ah yes. Did so, but no luck still (Same error - updated branch above). Am I missing some sort of webpack config needed for TS + Next & Storybook to play nice?
I can’t try that on my computer until tomorrow, but could you add ".storybook" directory to include in main.ts?
include: [path.resolve(__dirname, '../src'), __dirname],
TBH I’m not sure if preview.tsx is supported at all. If adding __dirname won’t help, I’d try changing preview.tsx to preview.jsx and main.ts to main.js 🤔
Thanks, @hasparus, it looks like it's working when I've implemented your changes. (I haven't checked if Jest is working properly but I'll assume it's working for now.)
EDIT: The main.ts & preview.tsx files are still read as JS, not as TS, unfortunately.
Here are my current files:
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"noUnusedLocals": true,
"sourceMap": true,
"baseUrl": ".",
"declaration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"outDir": "build/lib",
"paths": {
"@App/*": ["src/*"]
},
"rootDirs": ["src"]
},
"exclude": ["node_modules", "build", "scripts"],
"include": ["next-env.d.ts", "src/**/*"]
}
const { pathsToModuleNameMapper } = require('ts-jest/utils')
const { compilerOptions } = require('./tsconfig')
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
/**
* Make tsconfig paths work in Jest
* https://kulshekhar.github.io/ts-jest/user/config/#jest-config-with-helper
*/
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
// Code below is from Storybook TS docs (unsure if needed if using the ts-jest preset above)
transform: {
'.(ts|tsx)': 'ts-jest',
},
testPathIgnorePatterns: ['/node_modules/', '/lib/'],
testRegex: '(/test/.*|\\.(test|spec))\\.(ts|tsx)$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'json']
}
const path = require('path')
module.exports = {
stories: ['../src/**/*.stories.(tsx|mdx)'],
addons: [
// Addons
'@storybook/addon-a11y/register',
'@storybook/addon-actions/register',
'@storybook/addon-knobs/register',
'@storybook/addon-links/register',
'@storybook/addon-storysource/register',
// Presets
{
name: '@storybook/preset-typescript',
options: {
tsLoaderOptions: {
configFile: path.resolve(__dirname, './tsconfig.json'),
},
tsDocgenLoaderOptions: {
tsconfigPath: path.resolve(__dirname, './tsconfig.json'),
},
forkTsCheckerWebpackPluginOptions: {
colors: false, // disables built-in colors in logger messages
},
include: [
path.resolve(__dirname, '../src'),
path.resolve(__dirname, '../.storybook'),
],
},
},
],
}
import React from 'react'
import { render } from 'react-dom'
import { withA11y } from '@storybook/addon-a11y'
import { withInfo } from '@storybook/addon-info'
import { addDecorator, configure } from '@storybook/react'
import { GlobalStyle } from '../src/styles/global'
addDecorator(withInfo)
addDecorator(withA11y)
const loadStories = () => {
/**
* Add GlobalStyles to stories without re-mounting for each story.
* https://github.com/storybookjs/storybook/issues/5578#issuecomment-494656470
*/
const globalStyleElId = 'global-style'
const globalStyleEl =
document.querySelector(`#${globalStyleElId}`) ||
(() => {
const el = document.createElement('div')
el.id = globalStyleElId
document.head.append(el)
return el
})()
render(<GlobalStyle />, globalStyleEl)
}
configure(loadStories, module)
{
"extends": "../tsconfig.json",
"compilerOptions": {
"isolatedModules": false,
"jsx": "react"
},
"include": ["./**/*"]
}
I didn't see your post just cloned your code too check if it really works lol :D It works indeed. I'm glad.
~~This means we could mention main.ts
in the docs. I didn't know it's supported.
https://storybook.js.org/docs/configurations/typescript-config/#setting-up-typescript-to-work-with-storybook~~
Edit: Ok. It isn't :D I got BABEL_PARSE_ERROR
after defining a type in main.ts. Looks like it's just treated as JavaScript.
I was playing around with main.ts
the other day & don't remember off the top of my head, but it's something to do with your project's settings. I think I fixed it by setting "target": "es5"
in tsconfig.json
.
@hasparus oh yeah - it looks like it's just javascript. I tried changing target
to es5 & playing with lib
in tsconfig but couldn't get types to work. :|
FWIW me and the team at Curve have always had issues with v1.2.0 of the TypeScript preset. Fixing the package version to 1.1.0 ensures everything works without having to change from the default preset config.
@shilman you were actually able to get a main.ts
file working? I've been failing at this today. i'm considering opening an issue.
@stephenkoo, just to be clear you weren't able to get a main.ts
file working (as opposed to main.js
)
@sentilesdal yes I was able to get it working, after some fiddling. I don't think we officially support it though--I didn't even know it was possible until somebody mentioned it in another issue.
@sentilesdal I wasn't able to get the ts
file to be read as ts (type declarations caused errors), but it was read as js fine.
@shilman thanks for the response. any clues on how to do this? I tried to launch storybook with ts-node
but that still didn't do the trick. I'd really like to be able to import from our project's webpack.config.ts which I can only do if this main file is typescript :).
do you think it's worth opening an issue to get official support for this?
thanks in advance!
@sentilesdal What I observed when I was testing is that Storybook uses Babel's typescript handling and that my main.ts
was getting automatically transpiled on load. However, my tsconfig wasn't properly set up and I had to tweak it.
I think that properly supporting this requires modifying Storybook to run its own loader logic on this file at load-time, rather than relying on the user's configuration. I think it's already doing this for manager.[tj]s
and preview.[tj]s
.
Please feel free to open an issue, and hopefully somebody from the community can take it on.
FWIW, I've managed to work with ts and next using :
plain JS files for main.js and preview.js
an extended tsconfig.json inside .storybook (with jsx: react)
importing React at the top of any components used in storybook AND stories.
Still not perfect, but good for our usage.
Hi everyone! Seems like there hasn't been much going on in this issue lately. If there are still questions, comments, or bugs, please feel free to continue the discussion. Unfortunately, we don't have time to get to every issue. We are always open to contributions so please send us a pull request if you would like to help. Inactive issues will be closed after 30 days. Thanks!
Following up on @Djiit's suggestion, we've got it working with a similar approach, however without the need for the React
imports thanks to babel-plugin-react-require
- as suggested in the Storybook FAQs.
However, this only seems to work when we create the following .babelrc
in the root directory:
{
"presets": ["next/babel"], // necessary for next.js
"plugins": ["react-require"]
}
If I move it to the .storybook
directory (without the next/babel
preset) we get an error when trying to load JSX:
Error: Module parse failed: Unexpected token (6:30)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| title: "Button"
| };
> export const withText = () => <Button>Hello Button</Button>;
| export const withEmoji = () => <Button>
| <span role="img" aria-label="so cool">
at Object../src/components/Button/index.stories.tsx (http://localhost:55727/main.a47420a434be88f4dd23.bundle.js:61:7)
at __webpack_require__ (http://localhost:55727/runtime~main.a47420a434be88f4dd23.bundle.js:785:30)
at fn (http://localhost:55727/runtime~main.a47420a434be88f4dd23.bundle.js:151:20)
at webpackContext (http://localhost:55727/main.a47420a434be88f4dd23.bundle.js:35:9)
at http://localhost:55727/vendors~main.a47420a434be88f4dd23.bundle.js:3878:31
at Array.forEach (<anonymous>)
at http://localhost:55727/vendors~main.a47420a434be88f4dd23.bundle.js:3877:22
at Array.forEach (<anonymous>)
at http://localhost:55727/vendors~main.a47420a434be88f4dd23.bundle.js:3876:14
at render (http://localhost:55727/vendors~main.a47420a434be88f4dd23.bundle.js:1897:13)
I've looked through the docs but there seems to be no mention of extending the base Storybook babel config - but I have a feeling that may be what we need to do (?)
We're using the @storybook/preset-typescript
add-on for TS support if that's of any help (and have no custom webpack config).
Edit: After some more messing about, it seems that just with the next/babel
preset (without react-require
plugin) in the root .storybook directory it works fine! 🤔
Hi everyone! Seems like there hasn't been much going on in this issue lately. If there are still questions, comments, or bugs, please feel free to continue the discussion. Unfortunately, we don't have time to get to every issue. We are always open to contributions so please send us a pull request if you would like to help. Inactive issues will be closed after 30 days. Thanks!
For me manager.tsx
seems to work,
but for some reason I cannot import a react component from a relative path:
ERROR in ./.storybook/manager.tsx
Module not found: Error: Can't resolve './panels/SourceCode' in '/my/repo/.storybook'
with $ ls -la .storybook/panels
drwxr-xr-x 2 matheo matheo 4096 may 18 21:03 .
drwxr-xr-x 3 matheo matheo 4096 may 18 21:03 ..
-rw-r--r-- 1 matheo matheo 1333 may 18 21:03 SourceCode.tsx
-rw-r--r-- 1 matheo matheo 2612 may 18 21:03 Tabs.tsx
tsx
files have the corresponding webpack loader and resolve.extensions, so I don't get why it's not found with the relative path to manager.tsx
. I don't get it :(
@matheo see #9773
@ndelangen added that issue to the breaking changes milestone, can you grab it?
@shilman interesting
perhaps my issue is not with the addons
path, but a simple import tho:
import { SourceCodePanel } from './panels/SourceCode';
from .storybook/manager.tsx
with a existing .storybook/panels/SourceCode.tsx
, so it seems that manager.tsx
is able to import only js
files (because I have a theme.js
and compodoc.json
imported without problems), but it's not resolving this tsx component. I may need to transpile them but I wonder if there's a webback/tsconfig option I'm missing :(
Edit: Ahh! now I see that main.js
affects the Preview webpack config
, but the Manager webpack config
doesn't have .tsx
in the module.resolve.extensions
!! perhaps it has the rule already configured to use babel-loader with /\.(mjs|tsx?|jsx?)$/
.
I solved it via #10839
Have just run into this exact issue - once my config.js
tries to import a TypeScript file, it fails to resolve. Were you able to find any kind of workaround @matheo ?
We've just released zero-config typescript support in 6.0-beta. Please upgrade and test it!
Thanks for your help and support getting this stable for release!
Thanks @shilman - installing it today. 🤞
Edit: Gave 6.0-beta a go, unfortunately it's still not resolving anything with ts/.tsx file extensions.
@terenceodonoghue bummer.. ☹️ do you have a repro repo we could look at?
@shilman I recreated the issue in a test repo here: https://github.com/terenceodonoghue/sb-9610
Let me know if I can help further.
@terenceodonoghue Took a quick look and wasn't immediately obvious, but it's a super simple repro (great job!) so I'll get to the bottom of it. Thanks so much!!!
@shilman want to debug together?
@terenceodonoghue bunch of issues in the project, none storybook related:
1) you need to add storybook to an existing working project. storybook is not meant to run on its own.
2) missing typescript dependency in package.json
(which would be there if it was a working typescript project)
3) bad import in .storybook/preview.js
=> import Container from "../src/components/Container";
4) Container component doesn't show children. added for debugging:
const Container: FunctionComponent = ({ children }) => (
<div style={{ margin: 5, backgroundColor: "#ff0" }}>{children}</div>
);
hope that helps! (and thanks to @mrmckeb!)
- bad import in
.storybook/preview.js
=>import Container from "../src/components/Container";
@shilman This is what fixed it, but the original export was done via an index.ts
file in the components folder - shouldn't this work, like it does with the js
extension?
With regards to the other points, noted, but it was only a demo repo for the purposes of reproducing this issue. 😄
@terenceodonoghue the repro needs to run tho, I commented those failures in your commit, the repro should show the error you're reporting, not a missing typescript dependency :-?
@terenceodonoghue I'm just saying when I fixed those problems, the repro ran as I'd expect it. Hope that helps!
Thanks @matheo, I added the missing TypeScript dependency. And thanks also @shilman, I'll hold off on upgrading for the time being since I'm still able to import from an index.ts
file in v5 using my own tsconfig.json
. Thanks for taking the time to debug nonetheless.
Hi guys, Storybook integration has improved a lot with v6, I've managed to set it up without needing a custom tsconfig
.
However I am still stuck at loading CSS modules, see a repro starter here and the result by running yarn run storybook
and opening http://localhost:6006/?path=/story/vns-cssmodule--basic
.
The module.css
import gets an empty object in Storybook, (but works normally in the app). Any insight?
My idea was to extend Next config, but the official FAQ does not seem to correctly answers the question.
It advise to share the Webpack config between Next and Storybook, agreed, but it does this by require the next.config.js
. Sadly, as far as I understand, this will only share the user's extension to Next's webpack config, but not the actual underlying Next webpack config. So basically it doesn't actually share Next's magic with Storybook.
Edit: I tried to add a .babelrc
that extends next/babel
but it does not work, that's probably unrelated.
Also, Styled JSX works out of the box, while I used to have a lot of issue when trying to build JSX that contained <style jsx>
. That's great news, but why? The new TS config is smarter about those?
Hi everyone! Seems like there hasn't been much going on in this issue lately. If there are still questions, comments, or bugs, please feel free to continue the discussion. Unfortunately, we don't have time to get to every issue. We are always open to contributions so please send us a pull request if you would like to help. Inactive issues will be closed after 30 days. Thanks!
Ah, stalebot, my favourite one. No, issue described just above is still happening, text is not blue with CSS modules and I still can't tell what would be a working setup so all Next (and TS) features work with Storybook.
Any updates on this? I need Storybook with Typescript on my Next.js app as well
Tried v6.0.0-rc.14
, getting File /path/to/main.ts is detected but impossible to import loader for .ts
error. I have main.ts
, manager.ts
, and preview.tsx
, but storybook loads blank. Are tsx?
extensions under .storybook
supported in v6?
I am Looking at a few issues for the official release of @next/plugin-storybook
.
If you're interested, check these issues out.
https://github.com/vercel/next.js/issues/15195 https://github.com/vercel/next.js/issues/15196 https://github.com/vercel/next.js/issues/15351#issuecomment-670599434
@matamatanot you may want to check our starter: https://github.com/VulcanJS/vulcan-next I've tried to migrate to Storybook 6, sadly I am hitting some weird issues, either at buildtime on Mac and Ubuntu 20, or at runtime (on Ubuntu 18): see https://github.com/storybookjs/storybook/issues/10933 I am using a pretty common setup, using Next core features + Material UI and Styled Components, so nothing fancy.
Rollbacking to v5 means a lot more TS setup.
Definitely not stale, still having issues in Vulcan to setup Next + TS + Storybook 6
Not stale. We have a working example in Vulcan with Storybook v6, TS, Next.js, but there is the very last issue of CSS module still not being correctly applied. Not significant yet it can become problematic if you actually use CSS modules in your frontend.
For anyone interested with Storybook with Next.js 10 + TS 4.1 + jest + cypress 6 + Emotion 11 + tons of other stuff, check out https://github.com/UnlyEd/next-right-now/pull/251 (PR)
It's still a WIP, but I've fixed the most complicated issues I was meant to encounter (babel/webpack, react providers, mocks).
Static version auto-hosted on vercel, deployed by github actions automatically. Heavily documented, for my own sake. 😅
Describe the bug Following the TypeScript instructions & recommended config in the Storybook docs results in
TS2769: No overload matches this call
errors when runningbuild storybook
with Next.js.Specifically in my Next.js setup:
/src/stories/0-Welcome.stories.tsx(8,54)
2./src/stories/1-Button.stories.tsx(8,48)
To Reproduce Steps to reproduce the behavior:
yarn storybook
Expected behavior Storybook to run with no errors.
Screenshots
Code snippets
The following are changes & additions made to out-of-the-box Next.js & TS setup based on Storybook TS Config documentation + some Storybook addons
.storybook/main.ts:
.storybook/preview.ts:
jest.config.js
tsconfig.json (some are Next.js defaults, some are Storybook recommended tsconfig.js settings)
package.json scripts
System:
Additional context I'm just trying to set up the simplest Next.js, TS, Storybook (& Jest, Styled Components) setup with reasonable presets.