Storybook: Storyshot fail with Typescript

Created on 5 Mar 2019  ยท  18Comments  ยท  Source: storybookjs/storybook

I am trying to use storyshot with Typescript but I get an error that I don't manage to solve:

 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as React from 'react';

    SyntaxError: Unexpected token *

I also tried to follow https://medium.com/@mtiller/storybook-react-typescript-and-jest-c9059ea06fa7 without success.

To Reproduce

yarn add --dev @storybook/addon-storyshots
yarn add --dev @types/storybook__addon-storyshots

In my source folder I add a storybook.test.ts

import initStoryshots from '@storybook/addon-storyshots';
initStoryshots();

The wepack config is

module.exports = (baseConfig, env, config) => {
    config.module.rules.push({
        test: /\.(ts|tsx)$/,
        use: [
            {
                loader: require.resolve('ts-loader'),
            },
        ],
    });
    config.resolve.extensions.push('.ts', '.tsx');

    config.module.rules.push({
        test: /\.stories\.tsx?$/,
        loaders: [
            {
                loader: require.resolve('@storybook/addon-storysource/loader'),
                options: { parser: 'typescript' },
            },
        ],
        enforce: 'pre',
    });
    return config;
};

and the jest config is

"jest": {
        "setupFiles": [
            "<rootDir>/setupTests.ts"
        ],
        "transform": {
            "\\.(ts|tsx)$": "ts-jest",
            "\\.css$": "<rootDir>/node_modules/razzle/config/jest/cssTransform.js",
            "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/node_modules/razzle/config/jest/fileTransform.js"
        },
        "testMatch": [
            "!**/flycheck_*",
            "<rootDir>/src/**/__tests__/**/*.(ts|js)?(x)",
            "<rootDir>/src/**/?(*.)(spec|test).(ts|js)?(x)"
        ],
        "moduleFileExtensions": [
            "ts",
            "tsx",
            "js",
            "json"
        ],
        "collectCoverageFrom": [
            "src/**/*.{js,jsx,ts,tsx}"
        ]
    },

Screenshots
image

storyshots bug has workaround inactive question / support typescript

Most helpful comment

Any strategies on loading all the stories into using one script like that?

I successfully use Barrelsby to generate a barrel that exports all *.stories.tsx files, then just require that single file.

package.json:

scripts: {
   "generate-barrels": "barrelsby --directory ./src/components --include .stories.tsx --name stories --location replace --delete"
}

.storybook/config.tsx:

function loadStories() {
   require("../src/components/stories");
}

All 18 comments

Bump, also hitting this.

It seems to happen when storyshots tries to load the storybook-config file, which contains code that's not just plain JS.

@apiel @DeX3 I was able to fix similar errors by renaming addons.js and config.js to addons.ts and config.ts

@dgreuel I tried out without success :-/

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 am encountering a similar issue where Jest throws on my storybook config.js file:

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { configure } from '@storybook/react';

    SyntaxError: Unexpected token {

 SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (../node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (../node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at configure (../node_modules/@storybook/addon-storyshots/dist/frameworks/configure.js:38:11)
      at Object.load (../node_modules/@storybook/addon-storyshots/dist/frameworks/react/loader.js:26:26)
      at loadFramework (../node_modules/@storybook/addon-storyshots/dist/frameworks/frameworkLoader.js:31:17)

Here are my files:
jest.config.js

module.exports = {
    roots: ['<rootDir>/../src'],
    transform: {
        '^.+\\.tsx?$': 'ts-jest'
    },
    testRegex: '[.]storyshot[.]tsx?$',
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};

config.storyshot.ts (the test running the storyshot)

import initStoryshots from '@storybook/addon-storyshots';

initStoryshots();

config.js

import { configure } from '@storybook/react';

// Loads all files ending with ".stories.ts" or ".stories.tsx" in 'src' directory.
const req = require.context('../src', true, /[.]stories[.](ts|js)x?$/);

function loadStories() {
    req.keys().forEach(fileName => req(fileName));
}

configure(loadStories, module);

webpack.config.js

const webpackConfig = require('../webpack/webpack.config');

module.exports = async ({ config }) => ({
    ...config,
    module: {
        ...config.module,
        rules: webpackConfig.module.rules
    },
    resolve: {
        ...config.resolve,
        extensions: webpackConfig.resolve.extensions
    }
});

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "target": "es6",
        "jsx": "react"
    },
    "include": ["./src/**/*"]
}

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!

Same here. :(

same here

I had a similar error after upgrading today. This was the error message:

  โ— Test suite failed to run

    /var/www/html/node_modules/@dump247/storybook-state/dist/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
                                                                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected identifier

And this jest configuration helped:

{
    "transformIgnorePatterns": [
      "/node_modules/(?!@dump247).+(ts|tsx|js|jsx)$"
    ],
}

Not sure whether this helps someone.

To fix issues I went away from ts-jest and now use babel version.

https://jestjs.io/docs/en/getting-started

But there are still some tradeoffs - https://kulshekhar.github.io/ts-jest/user/babel7-or-ts

And it seems that ts-jest can't be used with storyshot, because webpack require fix is about babel(macro or plugin way).

So, my configs:

jest.config.js:

module.exports = {
  roots: ["<rootDir>/src"]
};

.babelrc:

{
  "presets": [["react-app", { "flow": false, "typescript": true }]]
}

.storybook/config.js:

import { configure, addDecorator, addParameters } from "@storybook/react";
import { withOptions } from "@storybook/addon-options";
import { create } from "@storybook/theming";
import requireContext from 'require-context.macro';

const theme = create({
  base: "dark",
  colorPrimary: "#FF4785",
  colorSecondary: "#1EA7FD"
});
addParameters({ options: { theme } });

const req = requireContext("../src", true, /.stories.tsx$/);

function loadStories() {
  req.keys().forEach(req);
}

addDecorator(
  withOptions({
    hierarchySeparator: /\/|\./,
    hierarchyRootSeparator: /\|/
  })
);

configure(loadStories, module);

(require-context.macro package is used)

webpack.config.js:

const path = require("path");

module.exports = ({ config, mode }) => {
  config.module.rules.push({
    test: /\.(ts|tsx)$/,
    loader: require.resolve('babel-loader'),
    options: {
      presets: [['react-app', { flow: false, typescript: true }]],
    },
  });

  config.module.rules.push({
    test: /\.stories\.tsx?$/,
    loaders: [
      {
        loader: require.resolve('@storybook/addon-storysource/loader'),
        options: { parser: 'typescript' }
      }
    ],
    enforce: 'pre',
  });

  config.resolve.extensions.push('.js', '.jsx', '.ts', '.tsx', '.json');

  return config;
};

Ran into the same issue. Very sad about this :(

We'd love to get some help fixing this, is anyone here able to help us?

For reference, the error in this thread only occurs when loading stories dynamically with require.context. If one were to load stories via just require('../src/stories/Example.stories') then it works with TypeScript.

For reference, the error in this thread only occurs when loading stories dynamically with require.context. If one were to load stories via just require('../src/stories/Example.stories') then it works with TypeScript.

Any strategies on loading all the stories into using one script like that?

Any strategies on loading all the stories into using one script like that?

I successfully use Barrelsby to generate a barrel that exports all *.stories.tsx files, then just require that single file.

package.json:

scripts: {
   "generate-barrels": "barrelsby --directory ./src/components --include .stories.tsx --name stories --location replace --delete"
}

.storybook/config.tsx:

function loadStories() {
   require("../src/components/stories");
}

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!

Hey there, it's me again! I am going close this issue to help our maintainers focus on the current development roadmap instead. If the issue mentioned is still a concern, please open a new ticket and mention this old one. Cheers and thanks for using Storybook!

Still having problems

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { configure } from '@storybook/react';

    SyntaxError: Unexpected token {

 SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (../node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (../node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at configure (../node_modules/@storybook/addon-storyshots/dist/frameworks/configure.js:38:11)
      at Object.load (../node_modules/@storybook/addon-storyshots/dist/frameworks/react/loader.js:26:26)
      at loadFramework (../node_modules/@storybook/addon-storyshots/dist/frameworks/frameworkLoader.js:31:17)

Tried to use the require-context.macro package, but had the same issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rpersaud picture rpersaud  ยท  3Comments

xogeny picture xogeny  ยท  3Comments

tomitrescak picture tomitrescak  ยท  3Comments

zvictor picture zvictor  ยท  3Comments

tirli picture tirli  ยท  3Comments