Storybook: Addon-docs: Source doc block Typescript support

Created on 20 Aug 2019  ·  69Comments  ·  Source: storybookjs/storybook

Describe the bug
As documented in the Technical Preview guide, using typescript without passing sourceLoaderOptions: null into the docs preset causes the following error:

Variable '__MODULE_DEPENDENCIES__' implicitly has an 'any[]' type

This is unfortunately not fixed by updating the storybook tsconfig.json to use "noImplicitAny": false.

To Reproduce
Steps to reproduce the behavior:

  1. Write a story for addon-docs using Typescript and the docs preset
  2. Run storybook

Expected behavior
Docs page loads, as usual, and a code snippet is available for the story.

Screenshots
If applicable, add screenshots to help explain your problem.

Code snippets
presets.js:

{
  name: '@storybook/addon-docs/react/preset',
  options: {
    sourceLoaderOptions: null,
  },
}

System:
Environment Info:

System:
OS: macOS 10.14.5
CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Binaries:
Node: 10.16.0 - /usr/local/opt/node@10/bin/node
Yarn: 1.17.3 - ~/workspace/component-library/node_modules/.bin/yarn
npm: 6.9.0 - /usr/local/opt/node@10/bin/npm
Browsers:
Chrome: 76.0.3809.100
Safari: 12.1.1
npmPackages:
@storybook/addon-a11y: ^5.2.0-beta.36 => 5.2.0-beta.38
@storybook/addon-actions: ^5.2.0-beta.36 => 5.2.0-beta.38
@storybook/addon-docs: ^5.2.0-beta.36 => 5.2.0-beta.38
@storybook/addon-knobs: ^5.2.0-beta.36 => 5.2.0-beta.38
@storybook/addon-links: ^5.2.0-beta.36 => 5.2.0-beta.38
@storybook/addon-viewport: ^5.2.0-beta.36 => 5.2.0-beta.38
@storybook/addons: ^5.2.0-beta.36 => 5.2.0-beta.38
@storybook/preset-scss: 1.0.2 => 1.0.2
@storybook/preset-typescript: 1.1.0 => 1.1.0
@storybook/react: ^5.2.0-beta.36 => 5.2.0-beta.38
@storybook/theming: ^5.2.0-beta.36 => 5.2.0-beta.38

docs storysource source compatibility with other tools has workaround inactive typescript

Most helpful comment

A temporary solution if you use awesome-typescript-loader:

/* tsconfig.json */
{
  "compilerOptions": { },
  "awesomeTypescriptLoaderOptions": {
    "ignoreDiagnostics": [7005]
  }
}

Not ideal, but it works.

All 69 comments

Thanks @enagy27! There are at least a few options here:

1) source-loader can output typescript-friendlier code
2) user can configure typescript differently (haven't seen this in our monorepo)
3) source-loader can output @ts-ignore to workaround

I'm thinking third option is the most straightforward to start, first is probably best long-term

Great Caesar's ghost!! I just released https://github.com/storybookjs/storybook/releases/tag/v5.2.0-beta.39 containing PR #7831 that references this issue. Upgrade today to try it out!

You can find this prerelease on the @next NPM tag.

Closing this issue. Please re-open if you think there's still more to do.

@enagy27 don't have a repro, so it would be great if you could give this a try and let me know if it works

@shilman absolutely! Giving it a shot now. Thank you!

@shilman still seeing these errors on beta.39 😞

ERROR in /Users/eric.nagy/workspace/component-library/src/elements/tag/tag.stories.tsx
./src/elements/tag/tag.stories.tsx
[tsl] ERROR in /Users/eric.nagy/workspace/component-library/src/elements/tag/tag.stories.tsx(69,52)
      TS7005: Variable '__MODULE_DEPENDENCIES__' implicitly has an 'any[]' type.

ERROR in /Users/eric.nagy/workspace/component-library/src/elements/tag/tag.stories.tsx
./src/elements/tag/tag.stories.tsx
[tsl] ERROR in /Users/eric.nagy/workspace/component-library/src/elements/tag/tag.stories.tsx(74,3)
      TS2300: Duplicate identifier 'parameters'.

Results of npx -p @storybook/cli@next sb info

Environment Info:

  System:
    OS: macOS 10.14.5
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
  Binaries:
    Node: 10.16.0 - /usr/local/opt/node@10/bin/node
    Yarn: 1.17.3 - ~/workspace/component-library/node_modules/.bin/yarn
    npm: 6.9.0 - /usr/local/opt/node@10/bin/npm
  Browsers:
    Chrome: 76.0.3809.100
    Safari: 12.1.1
  npmPackages:
    @storybook/addon-a11y: ^5.2.0-beta.39 => 5.2.0-beta.39 
    @storybook/addon-actions: ^5.2.0-beta.39 => 5.2.0-beta.39 
    @storybook/addon-docs: ^5.2.0-beta.39 => 5.2.0-beta.39 
    @storybook/addon-knobs: ^5.2.0-beta.39 => 5.2.0-beta.39 
    @storybook/addon-links: ^5.2.0-beta.39 => 5.2.0-beta.39 
    @storybook/addon-viewport: ^5.2.0-beta.39 => 5.2.0-beta.39 
    @storybook/addons: ^5.2.0-beta.39 => 5.2.0-beta.39 
    @storybook/preset-scss: 1.0.2 => 1.0.2 
    @storybook/preset-typescript: 1.1.0 => 1.1.0 
    @storybook/react: ^5.2.0-beta.39 => 5.2.0-beta.39 
    @storybook/theming: ^5.2.0-beta.39 => 5.2.0-beta.39

Given that this is on the source loader, does that need to be installed separately and then it's taken up by the preset, or is a new release of the preset required?

@enagy27 can you take a look at the loaded source using the instructions here and see if the loaded source includes the change in #7831? (replace .mdx with .tsx and the rest of it should apply)

https://github.com/storybookjs/storybook/blob/next/addons/docs/docs/faq.md#how-do-i-debug-my-mdx-story

@shilman I'm only able to start the server when sourceLoaderOptions: null is in effect 😞 otherwise a failing build halts starting up the server and I'm unable to inspect the source in-browser. Is there maybe a command line option to by-pass and start the server anyway on first failing build?

Whoopee!! I just released https://github.com/storybookjs/storybook/releases/tag/v5.2.0-beta.40 containing PR #7845 that references this issue. Upgrade today to try it out!

You can find this prerelease on the @next NPM tag.

@enagy27 Merged & released your changes. Give it a try?

@shilman no such luck 😞 I'm experimenting locally and can't seem to get the hang of it. I even cheated and marked them all as as any but it looks like then it complains about duplicate variable parameters, which makes me wonder if __STORY__ isn't being escaped properly? But then I can't see how it would be working for JS and not TS... I'm stumped

I am also experiencing this issue but unfortunately don't have much additional context.

Another solution here is to override all of the "strict" typechecking rules in the tsconfig.js file that storybook loads (either your project's tsconfig or a .storybook/tsconfig.js (I think)).

I think these are the ones to make sure aren't enabled:
image

@libetl I know you're really busy but it would be awesome if you could take a look at this one.

@JonKrone when you do this do you see the source code in the docs tab? I've made these modifications and I'm still not seeing source 😞

A temporary solution if you use awesome-typescript-loader:

/* tsconfig.json */
{
  "compilerOptions": { },
  "awesomeTypescriptLoaderOptions": {
    "ignoreDiagnostics": [7005]
  }
}

Not ideal, but it works.

@shilman Is this what you're looking for? FYI this wouldn't build without ignoring TS7005 (no implicit any).

  // @ts-ignore
  var withSourceLoader = require('@storybook/source-loader/preview').withSource;
  // @ts-ignore
  var __SOURCE_PREFIX__ = "/home/user/projects/real/ts/my-blog-react/src/graphql";
  // @ts-ignore
  var __STORY__ = "import React from \"react\";\n\nimport { ApolloProvider } from \"@apollo/react-hooks\";\nimport { storiesOf } from \"@storybook/react\";\n\nimport { Posts } from \"../views/Posts/index\"; // ! Fix coupling\nimport { PostContent } from \"../views/PostContent\"; // ! Fix coupling\nimport { withPostContentQuery } from \"./components/withPostContentQuery\";\nimport { withPostsQuery } from \"./components/withPostsQuery\";\nimport * as fakeQl from \"./fakeql/fakeql-endpoints\";\nimport apolloClientFactory from \"./apollo\";\n\n// FIXME: #coupling - find a way to not depend on Post and Container, probably fakes - but not good enough.\n\nconst apolloClient = apolloClientFactory(fakeQl.normalApiEndpoint);\nconst PostContentQuery = withPostContentQuery(PostContent);\nconst PostsQuery = withPostsQuery(Posts);\n\n// ~~~ Posts ~~~\nstoriesOf(\"GraphQL\", module).add(\"PostsQuery\", () => (\n  <ApolloProvider client={apolloClient}>\n    <PostsQuery routeHandler={() => null} />\n  </ApolloProvider>\n));\n\n// ~~~ PostContent ~~~\nstoriesOf(\"GraphQL\", module).add(\"PostContentQuery\", () => (\n  <ApolloProvider client={apolloClient}>\n    <PostContentQuery postId=\"1\" />\n  </ApolloProvider>\n));\n";
  // @ts-ignore
  var __ADDS_MAP__ = {"graphql--postsquery":{"startLoc":{"col":33,"line":20},"endLoc":{"col":1,"line":24},"startBody":{"col":47,"line":20},"endBody":{"col":1,"line":24}},"graphql--postcontentquery":{"startLoc":{"col":33,"line":27},"endLoc":{"col":1,"line":31},"startBody":{"col":53,"line":27},"endBody":{"col":1,"line":31}}};
  // @ts-ignore
  var __MAIN_FILE_LOCATION__ = "/root.stories.tsx";
  // @ts-ignore
  var __MODULE_DEPENDENCIES__ = [];
  // @ts-ignore
  var __LOCAL_DEPENDENCIES__ = {};
  // @ts-ignore
  var __IDS_TO_FRAMEWORKS__ = {};

  import React from "react";

import { ApolloProvider } from "@apollo/react-hooks";
import { storiesOf } from "@storybook/react";

import { Posts } from "../views/Posts/index"; // ! Fix coupling
import { PostContent } from "../views/PostContent"; // ! Fix coupling
import { withPostContentQuery } from "./components/withPostContentQuery";
import { withPostsQuery } from "./components/withPostsQuery";
import * as fakeQl from "./fakeql/fakeql-endpoints";
import apolloClientFactory from "./apollo";

// FIXME: #coupling - find a way to not depend on Post and Container, probably fakes - but not good enough.

const apolloClient = apolloClientFactory(fakeQl.normalApiEndpoint);
const PostContentQuery = withPostContentQuery(PostContent);
const PostsQuery = withPostsQuery(Posts);

// ~~~ Posts ~~~
storiesOf("GraphQL", module).addParameters({ storySource: { source: __STORY__, locationsMap: __ADDS_MAP__ } }).addDecorator(withSourceLoader(__STORY__, __ADDS_MAP__,__MAIN_FILE_LOCATION__,__MODULE_DEPENDENCIES__,__LOCAL_DEPENDENCIES__,__SOURCE_PREFIX__,__IDS_TO_FRAMEWORKS__)).add("PostsQuery", () => (
  <ApolloProvider client={apolloClient}>
    <PostsQuery routeHandler={() => null} />
  </ApolloProvider>
));

// ~~~ PostContent ~~~
storiesOf("GraphQL", module).addParameters({ storySource: { source: __STORY__, locationsMap: __ADDS_MAP__ } }).addDecorator(withSourceLoader(__STORY__, __ADDS_MAP__,__MAIN_FILE_LOCATION__,__MODULE_DEPENDENCIES__,__LOCAL_DEPENDENCIES__,__SOURCE_PREFIX__,__IDS_TO_FRAMEWORKS__)).add("PostContentQuery", () => (
  <ApolloProvider client={apolloClient}>
    <PostContentQuery postId="1" />
  </ApolloProvider>
));


@0b10 I'll give it a shot, thank you! We are currently ignoring all of those lines, but I hadn't thought to change my tsconfig.json as well 🤔

I was getting errors here after updating storybook-react-router to 1.0.6, which has an issue open: gvaldambrini/storybook-router#42 I'm not getting errors here (storybook-router errors were probably not related, see below comment)

"No code avaliable" on my TSX stories, MDX works fine, result looks similar/exactly like @0b10's story

  // @ts-ignore
  var withSourceLoader = require('@storybook/source-loader/preview').withSource;
  // @ts-ignore
  var __SOURCE_PREFIX__ = "C:\\Workspace\\application-ui\\src\\components\\atoms\\container";
  // @ts-ignore
  var __STORY__ = "import { storiesOf } from \"@storybook/react\";\nimport React, { ReactElement } from \"react\";\n\nimport { Container } from \"components\";\n\nconst stories = storiesOf(\"Atoms/Container\", module).addParameters({ component: Container });\n\nstories.add(\"Default\", (): ReactElement => <Container>Hello</Container>);\n";
  // @ts-ignore
  var __ADDS_MAP__ = {};
  // @ts-ignore
  var __MAIN_FILE_LOCATION__ = "/Container.stories.tsx";
  // @ts-ignore
  var __MODULE_DEPENDENCIES__ = [];
  // @ts-ignore
  var __LOCAL_DEPENDENCIES__ = {};
  // @ts-ignore
  var __IDS_TO_FRAMEWORKS__ = {};

  import { storiesOf } from "@storybook/react";
import React, { ReactElement } from "react";

import { Container } from "components";

const stories = storiesOf("Atoms/Container", module).addParameters({ storySource: { source: __STORY__, locationsMap: __ADDS_MAP__ } }).addDecorator(withSourceLoader(__STORY__, __ADDS_MAP__,__MAIN_FILE_LOCATION__,__MODULE_DEPENDENCIES__,__LOCAL_DEPENDENCIES__,__SOURCE_PREFIX__,__IDS_TO_FRAMEWORKS__)).addParameters({ component: Container });

stories.add("Default", (): ReactElement => <Container>Hello</Container>);

Updated config.js as it was just docs: DocsPage

    docs: {
        container: DocsContainer,
        page: DocsPage,
    },

Presets:

module.exports = [
    {
        name: "@storybook/addon-docs/react/preset",
        options: {
            configureJSX: true,
        },
    },
];

Webpack config, possibly not needed?

    config.module.rules.push({
        exclude: /node_modules/,
        test: /\.(ts|tsx)$/,
        use: [
            {
                loader: require.resolve("babel-loader"),
                options: {
                    presets: [["react-app", { flow: false, typescript: true }]],
                },
            },
            {
                loader: require.resolve("react-docgen-typescript-loader"),
            },
        ],
    });

    config.module.rules.push({
        enforce: "pre",
        include: [path.resolve(__dirname, "../src")],
        loader: require.resolve("@storybook/source-loader"),
        test: /\.(stories|story)\.[tj]sx?$/,
    });

tsconfig.json includes "noImplicitAny": true and no ignoreDiagnostics 😕

No longer seeing issues with rc.4, but no source 😞 Though it looks like this is also marked in #6641, so now that the errors are no longer present, this issue may be a duplicate

I've found a workaround!

  • Instead of using sourceLoaderOptions: null, I used transpileOnly: true in my tsLoaderOptions
  • Follow the workaround in #8055, where there cannot be a top-level parameters variable
  • For some reason, the use of right-hand statements such as as 'optionA' | 'optionB' failed here and had to be converted to left-hand type declarations.

This fails:

const colors = {
  primary: 'primary',
  secondary: 'secondary',
};

const color = radios('color', colors, colors.primary) as ButtonColor;

This works:

const colors: Record<string, ButtonColor> = {
  primary: 'primary',
  secondary: 'secondary',
};

const color = radios('color', colors, colors.primary);

In hindsight this seems like an understandable source-loader issue with type inference 🤔 anyway, hope this helps!

@enagy27 You rock for figuring this out. I'm hoping that @libetl will come back online at some point in 5.3, and we can just upgrade source-loader so that these workarounds are not needed. Fingers crossed! 🤞

Hi. Can someone provide an example repo where storybook with react typescript and docs are working?

@simonhoss this is a great idea, i'm really struggling to get this working.

me too 😄

The TS instructions point you to react-docgen-typescript-loader which says to install addon-info but earlier in the documentation doesn't it says addon-docs is a replacement for addon-info? Would be super helpful to see a working setup of this with TS or some clear instructions in one place specifically for setting up addon-docs with TS.

Happy to contribute and help out but need to understand how these pieces fit together first! 👍

Now that docs has been released I may be able to take some time to update cra-ts-kitchen-sink to make sure we're all on the same page for configuration 🙂 it may be a week or so though... for now I'll provide my config:

.storybook/addons.js

import '@storybook/addon-knobs/register';
import '@storybook/addon-a11y/register';
import '@storybook/addon-actions/register';

.storybook/config.js

import { configure, addDecorator, addParameters } from '@storybook/react';
import { withA11y } from '@storybook/addon-a11y';
import { withKnobs } from '@storybook/addon-knobs';

import theme from './theme';
import '../stylesheets/gusto.scss';

// This file overrides styles from the global Gusto
// styles which interfere with Storybook styles
import './storybook.scss';

// Is your addon not showing up? Try looking for a `register` function
// and add it to .storybook/addons.js
addDecorator(withA11y);
addDecorator(withKnobs);

addParameters({
  // storybook built-in
  // more info available here:
  // https://storybook.js.org/docs/configurations/options-parameter/
  options: {
    showPanel: true,
    panelPosition: 'right',
    // https://storybook.js.org/docs/configurations/theming/
    theme,
  },
  knobs: {
    escapeHTML: false,
  },
  // viewport structure here:
  // https://github.com/storybookjs/storybook/tree/master/addons/viewport#use-custom-set-of-devices
  // viewport: {
  //   defaultViewport: 'iphone6',
  //   type: 'mobile',
  // },
});

configure(require.context('../src', true, /\.stories\.(js|jsx|ts|tsx|mdx)$/), module);

.storybook/presets.js

const path = require('path');

module.exports = [
  '@storybook/preset-scss',
  {
    name: '@storybook/preset-typescript',
    options: {
      // Point the loader here to override the root "noEmit" compilerOption
      tsLoaderOptions: {
        // Transpile only means no type-checking from storybook, which greatly speeds up
        // builds. Types will be checked as part of the normal build process. This may also
        // be necessary for loading story source
        transpileOnly: true,
        configFile: path.resolve(__dirname, 'tsconfig.json'),
      },
      // We must use our config to ensure props and their comments are loaded
      tsDocgenLoaderOptions: {
        tsconfigPath: path.resolve(__dirname, 'tsconfig.json'),
        // https://github.com/styleguidist/react-docgen-typescript#parseroptions
        propFilter: prop => {
          if (prop.parent) {
            return !prop.parent.fileName.includes('node_modules/@types/react/');
          }

          return true;
        },
      },
    },
  },
  '@storybook/addon-docs/react/preset',
];

.storybook/theme.js

I can't share this because it's internal to my company, but it's referenced in config.js.

.storybook/tsconfig.json

This file only serves to remove configurations in the root tsconfig.json that wouldn't make sense here in storybook.

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "noEmit": false
  }
}

Hi @enagy27 - thanks for this. I have kinda got this working with a custom webpack config. using the typescript preset for some strange reason stops me being able to import assets in storybook, ie - css files.

One small problem i'm up against is that my props table isn't able to infer types like this:

SomeType['property'] right now i'm seeing any in my table instead of a union, i wonder if there is a way around this.

Hi, @enagy27. thanks for this. I have got this working with the config you shared。but there is still some promble. It cannot generate component description and props description when I write component with tsx. but it work with jsx。
image
image
image

Hi @zerofront. i had to follow this exact comment pattern

Component desc:

/**
 * This is a component description and should sit directly above your component
 */

Prop desc:

/** I am a prop description and should sit directly above the interface property i am describing */

@enagy27 actually, I had followed the comment pattern you shown in my first picture

@zerofront you’ll need a Typescript type for the component. You can instead use export const Button: React.FC<BaseButtonProps> = props => {...}

👆 my setup with TS and docgen doesn't work with generics for some reason, created an issue here #8143 which explains

@zerofront I have exactly your issue. In props sections of your Button docs, Storybook is printing the defaultProps instead the BaseButtonProps interface. And I miss the description too. About subtitle, you can add it in the story file, in this way:

export default {
  title: 'Button',
  component: Button,
  parameters: {
    componentSubtitle: 'Handy status label',
  },
}

@zerofront In addition to what @enagy27 said.
In order to work with *.stories.tsx, you need to add something like this config:

.storybook/webpack.config.js

const path = require('path');
const include = path.resolve(__dirname, '../src');

module.exports = ({ config }) => {
  config.module.rules.push({
    test: /\.ts(x?)$/,
    exclude: /node_modules/,
    use: [
      {
        loader: require.resolve('babel-loader'),
        options: {
          presets: [['react-app', { flow: false, typescript: true }]],
        },
      },
    ],
    include,
  });
  return config;
};

@zerofront you’ll need a Typescript type for the component. You can instead use export const Button: React.FC<BaseButtonProps> = props => {...}

@zerofront @enagy27 yesterday I discovered that my issue (that was apparently the same of @zerofront) was caused exactly by the return type on function.

This fixed for me:

- import React from 'react'
+ import React, { FC } from 'react'

- export const Button: React.FC<Props>
+ export const Button: FC<Props>

Source:
https://github.com/strothj/react-docgen-typescript-loader/issues/42#issuecomment-535090697
And partially this note could be related:
https://github.com/strothj/react-docgen-typescript-loader#react-component-class-import

I hope this can help.

@sergiop @enagy27 thanks! eventually, the props table is work.
but there is still some problems.

If defaultProps isn't string type, It can not generate.
image

image

@zerofront I can confirm I have the same Issue. It is in my to-do list of issues to manage to fix. ;-)
If you want to search for the cause, you should probably start trying to understand if it’s related to storybook itself or to react-docgen-typescript-loader.

@zerofront maybe it's better to open a dedicated issue. ;-)

i've had luck setting default props whilst de-structuring props. Pretty sure it's worked with non string values too.

ie:

const Text = ({
text: 'Hello world'
}: Props) => <p>{text}</p>

i've had luck setting default props whilst de-structuring props. Pretty sure it's worked with non string values too.

ie:

const Text = ({
text: 'Hello world'
}: Props) => <p>{text}</p>

@sami616 I use default props same as you, but I don't see defaults for non-string as @zerofront already reported.

Ignore my comment, yes im having the same issue.

@sami616, as already told, I want to open a bug report on this, but before to do it I need to investigate a little on the codebase, to understand if the source of the issue is storybook or react-docgen-typescript-loader. In this way I'll open the issue on the right project.

@sami616 @sergiop
I install react-docgen-typescript-loader version 3.2.1
I found some code in node_modules/react-docgen-typescript-loader/dist/generateDocgenCodeBlock

var setDefaultValue = function(defaultValue) {
    return typescript_1.default.createPropertyAssignment(
      typescript_1.default.createLiteral('defaultValue'),
      // Use a more extensive check on defaultValue. Sometimes the parser
      // returns an empty object.
      defaultValue != null && typeof defaultValue === 'object' && 'value' in defaultValue && typeof defaultValue.value === 'string'
        ? typescript_1.default.createObjectLiteral([
            typescript_1.default.createPropertyAssignment(
              typescript_1.default.createIdentifier('value'),
              typescript_1.default.createLiteral(defaultValue.value),
            ),
          ])
        : typescript_1.default.createNull(),
    );
  };

&& typeof defaultValue.value === 'string'

this condition limit the typeof defaultProps.

And In the newest version 3.3.0 react-docgen-typescript-loader, It supoort string、number、boolean

https://github.com/strothj/react-docgen-typescript-loader/blob/master/src/generateDocgenCodeBlock.ts

const setDefaultValue = (
    defaultValue: { value: string | number | boolean } | null,
  ) =>
    ts.createPropertyAssignment(
      ts.createLiteral("defaultValue"),
      // Use a more extensive check on defaultValue. Sometimes the parser
      // returns an empty object.
      defaultValue != null &&
        typeof defaultValue === "object" &&
        "value" in defaultValue &&
        (typeof defaultValue.value === "string" ||
          typeof defaultValue.value === "number" ||
          typeof defaultValue.value === "boolean")
        ? ts.createObjectLiteral([
            ts.createPropertyAssignment(
              ts.createIdentifier("value"),
              ts.createLiteral(defaultValue!.value),
            ),
          ])
        : ts.createNull(),
    );

@zerofront, nice to know. I have 3.2.1 too. Later this morning I'm updating it to 3.3.0 to see if this will solve the issue. Thanks.

@zerofront I can confirm updating react-docgen-typescript-loader to 3.3.0 will solve the issue. Thanks.
Screenshot 2019-10-10 at 12 00 16

A temporary solution if you use awesome-typescript-loader:

/* tsconfig.json */
{
  "compilerOptions": { },
  "awesomeTypescriptLoaderOptions": {
    "ignoreDiagnostics": [7005]
  }
}

Not ideal, but it works.

I just updated from 5.1 to 5.2.5 today and started getting this error, without installing addon-docs yet. This solution worked for me, although I have to say it's not really clear to my why.

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!

I'm still getting the error described in this issue for version "@storybook/react": "5.2.6" and "react-docgen-typescript-loader": "3.6.0". Not sure if that's relevant, but the only file that has been added the // @ts-ignores to __MODULE_DEPENDENCIES__ in the PRs referenced here is src/server/build.js while it's still un-ignored in src/client/preview.js.

@jalooc please check out 5.3 beta. Tons of improvements to the props table.

@shilman I believe I tried this last on beta.6 and it wasn’t functioning without the workaround. I’ll try again with the latest 😄

I still get this problem with storybook 5.3.[email protected] and react-docgen-typescript-loader 3.6.0.

The only way to fix it for me was to set "noImplicitAny": false in tsconfig.json which I really don't want to do.

The error I am getting is this one:
TS7005: Variable '__MODULE_DEPENDENCIES__' implicitly has an 'any[]' type.

Even if I add a type to my stories it doesn't fix the problem fully.

Follow up, I got it working using the transpileOnly option mentioned by @enagy27. I am using presets instead of full webpack configs, this is currently my presets.js. No changing in the tsconfig.json:

// presets.js
const path = require("path");

module.exports = [
    {
        name: "@storybook/preset-typescript",
        options: {
            tsLoaderOptions: {
                configFile: path.resolve(__dirname, "../tsconfig.json"),
                transpileOnly: true,
            },
            tsDocgenLoaderOptions: {
                tsconfigPath: path.resolve(__dirname, "../tsconfig.json"),
            },
            include: [path.resolve(__dirname, "../src")],
        },
    },
    {
        name: "@storybook/addon-docs/react/preset",
        options: {
            configureJSX: true,
            //sourceLoaderOptions: null,
        },
    },
];

Any updates on this? We're trying to use storybook addons with TS and can't get past this even with the workarounds. Continue to receive
"Variable '__MODULE_DEPENDENCIES__' implicitly has an 'any[]' type."

Currently have tried updating storybook to 5.3.0-beta.16 and tried the other workarounds mentioned here. Thanks

I can't get storybook addon-docs to show the props table with typescript. It just says "No component found".

addons.js

import '@storybook/addon-knobs/register'
import '@storybook/addon-a11y/register'
import '@storybook/addon-docs/register'

presets.js

module.exports = [
  {
    name: "@storybook/addon-docs/react/preset",
    options: {
      configureJSX: true,
    }
  }
]

webpack.config.js

const path = require('path')
const SRC_PATH = path.join(__dirname, '../src')

module.exports = ({ config }) => {
    config.module.rules.push({
        test: /\.(ts|tsx|js|jsx)$/,
        include: [SRC_PATH],
        use: [
            {
                loader: require.resolve('babel-loader'),
                options: {
                    presets: [['react-app', { flow: false, typescript: true }]],
                    plugins: ['babel-plugin-styled-components']
                },
            },
            {
                loader: require.resolve('react-docgen-typescript-loader'),
                options: {
                    tsconfigPath: path.resolve(__dirname, '../tsconfig.json'),
                },
            },
            {
                loader: require.resolve('@storybook/source-loader'),
                options: { parser: 'typescript',  injectParameters: true, },
            },
        ],
        exclude: [/node_modules/],
        enforce: 'pre',

    })

    config.resolve.extensions.push('.ts', '.tsx', '.js', '.jsx')
    return config
}

Storybook 5.2.8
Addon-Docs 5.2.8
react-docgen-typescript-loader 3.6.0
babel-loader 8.0.6
@storybook/source-loader 5.2.8

Also, if I use Component Story Format storybook doesn't find the component at all (canvas and docs and menu are blank), but if I use storiesOf it displays them.

As a workaround you can point doc generation towards tsconfig.json with strict rules turned off. I guess I solved it like this for now. Can recheck next week if anyone interested.

these are my configurations , might help.
git it working complete.
Capture1
Capture2
Capture3
Capture4

++ its
export const AccordionItem
and i have no webpack.config.js

For anyone else still struggling, I've finally managed to get it to work after some painful debugging of react-docgen-typescript-loader.

React-docgen-typescript-loader assigns the __docgeninfo using the folder name, not the component name, so you must put your component in a folder of the same name (case sensitive).

|__
  CTALink
    |___index.tsx

I couldnt get CSF format to work (always blank), but when using the storiesOf syntax, you must include the component using the addParameters function from storybook in order for the props table to be picked up.

storiesOf('CTALink', module)
  .addParameters({
    component: CTALink,
  })
  .add('default story', () => (
    <CTALink to="/">Click here</CTALink>
  ))

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!

Typescript should be working in the source block in 5.3. Closing.

I have update both @storybook/reactand @storybook/addon-docs to 5.3.0-rc.4 but keep getting the error message TS7005: Variable '__MODULE_DEPENDENCIES__' implicitly has an 'any[]' type.

I'm not using the preset and also I'm new to webpack so probably I made some mistakes.
Here is my webpack.config.js:
```const path = require('path');

module.exports = {
node: {
fs: 'empty',
child_process: 'empty'
},
resolve: {
modules: [
'node_modules',
],
extensions: [".ts", ".tsx"],
symlinks: true
},
module: {
rules: [
{
test: /.(ts|tsx)$/,
use: [
{
loader: require.resolve('awesome-typescript-loader')
},
{
loader: require.resolve('react-docgen-typescript-loader')
},
]
},
{
test: /.(stories|story).[tj]sx?$/,
loader: require.resolve('@storybook/source-loader')
}
]
},
externals: {
'class-transformer': 'class-transformer'
}
};
```

Yo-ho-ho!! I just released https://github.com/storybookjs/storybook/releases/tag/v5.3.0-rc.5 containing PR #9272 that references this issue. Upgrade today to try it out!

You can find this prerelease on the @next NPM tag.

@JacopoBonta can you try the most recent release 5.3.0-rc.5?

Hello @shilman Thanks for the amazing support for docs combined with storybook.
I updated to 5.3.0-rc.5 and I still get the error TS7005: Variable '__MODULE_DEPENDENCIES__' implicitly has an 'any[]' type.

It works only if I add ignoreDiagnostics: [7005] to the ts-loader configuration as shown below.

file main.js:

const { addons } = require('@storybook/addons');
const path = require('path');
const tsImportPluginFactory = require('ts-import-plugin')

module.exports = {
  stories: ['../packages/**/*.stories.(tsx|mdx)'],
  presets: [
    {
      name: '@storybook/preset-typescript',
      options: {
        tsLoaderOptions: {
          configFile: path.resolve(__dirname, 'tsconfig.json'),
          ignoreDiagnostics: [7005],
          getCustomTransformers: () => ({
            before: [ tsImportPluginFactory(
              {
                libraryName: 'antd',
                style: 'css',
                libraryDirectory: 'es'
              }
            ) ]
          }),
        },
        tsDocgenLoaderOptions: {
          tsconfigPath: path.resolve(__dirname, 'tsconfig.json'),
        },
        forkTsCheckerWebpackPluginOptions: {
          colors: false, // disables built-in colors in logger messages
        },
        include: [path.resolve(__dirname, "../packages")]
      },
    },
    {
      name: '@storybook/addon-docs/preset',
      options: {
      }
    }],
  addons: [
    '@storybook/addon-docs/register',
    '@storybook/addon-knobs/register',
    '@storybook/addon-actions/register',
    '@storybook/addon-links/register'
  ],
};

@JacopoBonta can you try the most recent release 5.3.0-rc.5?

I'm sorry but upgrading to 5.3.0-rc.5 didn't work.
I have updated both @storybook/react and @storybook/addon-docs but keep getting the same error.

@JacopoBonta can you verify @esakal's workaround?

@JacopoBonta I see that you are using awesome-typescript-loader. I'm currently using other loader but when I used that one a month ago I did a similar workaround. for awesome-typescript-loader you should do the following:

/* tsconfig.json */
{
  "compilerOptions": { },
  "awesomeTypescriptLoaderOptions": {
    "ignoreDiagnostics": [7005]
  }
}

taken from here

Yes, it works. I was already using this workaround before but I was looking for a way without it.

Anyway, thanks for the helps I have appreciated a lot and happy new year 🎉

Thank you @esakal you solution is the best (for me) so far. I used to set transpileOnly: true to fix the TypeScript issues but that ofc had the effect of allowing more TypeScript errors to go through unnoticed.

My current, pretty minimal configuration (presets.js) looks like this:

const path = require("path");

module.exports = [
    {
        name: "@storybook/preset-typescript",
        options: {
            tsLoaderOptions: {
                configFile: path.resolve(__dirname, "../tsconfig.json"),
                ignoreDiagnostics: [7005],
            },
        },
    },
    {
        name: "@storybook/addon-docs/preset",
        options: {
            configureJSX: true,
        },
    },
];

Thank you!

Was this page helpful?
0 / 5 - 0 ratings