storybookjs / presets

🧩 Presets for Storybook
MIT License
424 stars 104 forks source link

Error occured when eject the cra-ts example #72

Open Mu-xue opened 4 years ago

Mu-xue commented 4 years ago

I download the cra-ts example and run :

  1. npm run eject
  2. npm run storybook

And the

WARNING in ./src/components/Button/Button.stories.tsx 7:20
Module parse failed: Unexpected token (7:20)
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
| export default { title: 'Button' };
| 
> export const Default: FC = () => (
|   <Button>{process.env.REACT_APP_TEST_VAR}</Button>
| );
 @ ./src sync \.stories\.(mdx|tsx?)$ ./components/Button/Button.stories.tsx
 @ ./.storybook/config.ts
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./node_modules/@storybook/addon-docs/dist/frameworks/common/../../../react/config.js ./.storybook/config.ts (webpack)-hot-middleware/client.js?reload=true&quiet=true

ERROR in ./src/components/Button/Button.stories.mdx
Module not found: Error: Can't resolve './Button' in '/Users/yongxuexie/Desktop/neko/src/components/Button'
 @ ./src/components/Button/Button.stories.mdx 9:0-30 28:15-21 40:27-33 43:21-27 47:8-14 54:50-56 56:19-25
 @ ./src sync \.stories\.(mdx|tsx?)$
 @ ./.storybook/config.ts
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./node_modules/@storybook/addon-docs/dist/frameworks/common/../../../react/config.js ./.storybook/config.ts (webpack)-hot-middleware/client.js?reload=true&quiet=true

Please help to fix it.

Dergash commented 4 years ago

Hello @Mu-xue!

I've encountered the same issue after ejecting my CRA app that used @storybook/preset-create-react-app, and based my thoughts on the following answer https://github.com/storybookjs/storybook/issues/6690 (typescript config advice from that issue didn't solve anything):

The CRA config doesn't support ejection right now, you'd need to write your own config in that case - as we no longer have a reliable source.

So, I'm entirely new to Storybook infrastructure, but my understanding of things is this: Storybook has its own webpack config, which is configurable through presets specifically @storybook/preset-create-react-app. After ejecting, as per above issue, this preset no longer valid so actual storybook launch degrades to its default webpack config, which is actually reported in console output: eject

Default webpack config is lacking support of typescript (your case, you've got a syntax error due to non-js :FC type declaration) and JSX (my case and from the issue above).

So, what you have to do now is restore JSX and typescript support with separate config by adressing Typescript Config and Storybook for React sections of documentantion.

I was able to restore my expected behaviour (jsx, typescript and ts props exctraction) from @storybook/preset-create-react-app with following manual configuration:

// .storybook/main.js
const path = require("path")

module.exports = {
    stories: ['../src/**/*.stories.(tsx|mdx)'],
    webpackFinal: async config => {
        config.module.rules.push({
          test: /\.(ts|tsx)$/,
          include: path.resolve(__dirname, "../src"),
          use: [
              // There is also a second option in documentation to use babel instead of ts-loader which should also work
              {
                loader: require.resolve('ts-loader'),
              },
              {
                  loader: require.resolve('react-docgen-typescript-loader'),
                  options: {
                    tsconfigPath: path.resolve(__dirname, "../tsconfig.json")
                  }
              }
          ],
        })
        config.resolve.extensions.push('.ts', '.tsx');
        return config
      },
    addons: [
        '@storybook/addon-docs'
    ]
}

and tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

This correspond to my original config which I had before ejecting my CRA:

// .storybook/main.js
module.exports = {
    stories: ['../src/**/*.stories.tsx'],
    addons: [
        {
            name: '@storybook/preset-create-react-app',
            options: {
                tsDocgenLoaderOptions: {},
            },
        },
        '@storybook/addon-docs'
    ]
}
andrey-lazarev commented 1 year ago

I was able to make it work with these changes:

Hello @Mu-xue!

I've encountered the same issue after ejecting my CRA app that used @storybook/preset-create-react-app, and based my thoughts on the following answer storybookjs/storybook#6690 (typescript config advice from that issue didn't solve anything):

The CRA config doesn't support ejection right now, you'd need to write your own config in that case - as we no longer have a reliable source.

So, I'm entirely new to Storybook infrastructure, but my understanding of things is this: Storybook has its own webpack config, which is configurable through presets specifically @storybook/preset-create-react-app. After ejecting, as per above issue, this preset no longer valid so actual storybook launch degrades to its default webpack config, which is actually reported in console output: eject

Default webpack config is lacking support of typescript (your case, you've got a syntax error due to non-js :FC type declaration) and JSX (my case and from the issue above).

So, what you have to do now is restore JSX and typescript support with separate config by adressing Typescript Config and Storybook for React sections of documentantion.

I was able to restore my expected behaviour (jsx, typescript and ts props exctraction) from @storybook/preset-create-react-app with following manual configuration:

// .storybook/main.js
const path = require("path")

module.exports = {
    stories: ['../src/**/*.stories.(tsx|mdx)'],
    webpackFinal: async config => {
        config.module.rules.push({
          test: /\.(ts|tsx)$/,
          include: path.resolve(__dirname, "../src"),
          use: [
              // There is also a second option in documentation to use babel instead of ts-loader which should also work
              {
                loader: require.resolve('ts-loader'),
              },
              {
                  loader: require.resolve('react-docgen-typescript-loader'),
                  options: {
                    tsconfigPath: path.resolve(__dirname, "../tsconfig.json")
                  }
              }
          ],
        })
        config.resolve.extensions.push('.ts', '.tsx');
        return config
      },
    addons: [
        '@storybook/addon-docs'
    ]
}

and tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

This correspond to my original config which I had before ejecting my CRA:

// .storybook/main.js
module.exports = {
    stories: ['../src/**/*.stories.tsx'],
    addons: [
        {
            name: '@storybook/preset-create-react-app',
            options: {
                tsDocgenLoaderOptions: {},
            },
        },
        '@storybook/addon-docs'
    ]
}

I was able to restore expected behaviour as well, but with a bit different webpack 4 config for storybook:

const path = require('path')

module.exports = {
  stories: [
    '../src/**/*.stories.mdx',
    '../src/**/*.stories.@(js|jsx|ts|tsx)',
  ], webpackFinal: async config => {
    config.module.rules.push({
        test: /\.(ts|tsx)$/,
        include: path.resolve(__dirname, '../src'),
        use: [// There is also a second option in documentation to use babel instead of ts-loader which should also work
          {
            loader: require.resolve('babel-loader'), options: {
              customize: require.resolve('babel-preset-react-app/webpack-overrides'),
              presets: [
                [require.resolve('babel-preset-react-app'), { runtime: 'automatic' }],
                [require.resolve('@babel/preset-env'), { targets: 'defaults' }],
              ],
              plugins: [
                [require.resolve('babel-plugin-named-asset-import'),
                  { loaderMap: { svg: { ReactComponent: '@svgr/webpack?-svgo,+titleProp,+ref![path]' } } },
                ],
              ],
            },
          }],
      }, {
        test: /\.ts$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      }, // Process any JS outside of the app with Babel.
      // Unlike the application JS, we only compile the standard ES features.
      {
        test: /\.(js|mjs)$/,
        exclude: /@babel(?:\/|\\{1,2})runtime/,
        loader: require.resolve('babel-loader'),
        options: {
          babelrc: false,
          configFile: false,
          compact: false,
          presets: [
            [require.resolve('babel-preset-react-app/dependencies'), { helpers: true }],
          ],
          cacheDirectory: true, // See #6846 for context on why cacheCompression is disabled
          cacheCompression: false, // Babel sourcemaps are needed for debugging into node_modules
          // code.  Without the options below, debuggers like VSCode
          // show incorrect code and set breakpoints on the wrong lines.
          sourceMaps: true,
          inputSourceMap: true,
        },
      }, {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', {
          loader: 'postcss-loader',
          options: { plugins: () => [require('autoprefixer')()] },
        }, 'sass-loader'],
      })
    config.resolve.extensions.push('.ts', '.tsx')
    return config
  }, addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
  ],
}