Encountering errors while adding Storybook to a TypeScript-react project with existing stories

I recently added storybook to my TypeScript React project, but I encountered an error when running yarn storybook. The issue seems to be related to the "as" keyword in the generated code.

-- Error message
Parsing error: Missing semicolon

  10 |     backgroundColor: { control: 'color' }
  11 |   }
> 12 | } as Meta;
     |  ^
  13 |
  14 | const Template: Story<ButtonProps> = (args) => <Button {...args} />;

-- code 

export default {
  title: 'Example/Button',
  component: Button,
  argTypes: {
    backgroundColor: { control: 'color' }
  }
} as Meta;

-- my eslint config
{
  "env": {
    "es6": true,
    "node": true,
    "browser": true,
    "jest": true
  },
  "plugins": ["react", "prettier"],
  "extends": [
    "airbnb",
    "prettier",
    "eslint:recommended", // Uses the recommended rules from @eslint-plugin-react
    "plugin:react/recommended"
  ],

  "parserOptions": {
    "ecmaVersion": 2020,
    "sourceType": "module",
    "allowImportExportEverywhere": true,
    "ecmaFeatures": {
      "jsx": true // Allows for the parsing of JSX
    }
  },
  "rules": {
    "prettier/prettier": "error",
    "no-console": "warn",
    "import/first": "warn",
    "quotes": ["error", "single", { "avoidEscape": true }],
    "react/jsx-filename-extension": [1, { "extensions": [".tsx", ".ts"] }],
    "jsx-quotes": [2, "prefer-single"],
    "indent": ["error", 2],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
    ]
  },
  "parser": "babel-eslint",
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    },
    "react": {
      "version": "latest" // "detect" automatically picks the version you have installed.
    }
  }
}

Answer №1

I encountered a similar issue and found that creating a .babelrc.json file in the project's root directory with the following configuration resolved it for me. Make sure to install these dependencies:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "babel-plugin-transform-scss"
  ]
}

Answer №2

Seems like a crucial piece missing from your babelrc file is the @babel/preset-typescript preset.

Take a look at how I've set up my .babelrc:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "babel-plugin-transform-scss"
  ]
}

To add the missing preset, you can use either of these commands:

  • npm install --save-dev @babel/preset-typescript
    or -
  • yarn add -D @babel/preset-typescript

I have included other presets for a react project in mine, but I hope this resolves your issue!

You can find more information in the official documentation: https://babeljs.io/docs/en/babel-preset-typescript#installation

Wishing you well 😊

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Exploring the process of extracting data from a JSON URL using NextJS, TypeScript, and presenting the

After tirelessly searching for a solution, I found myself unable to reach a concrete conclusion. I was able to import { useRouter } from next/router and successfully parse a local JSON file, but my goal is to parse a JSON object from a URL. One example of ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

Can JSON Web Tokens be utilized in a browser environment?

Searching for a way to parse the JWT token led me to this jsonwebtoken library https://www.npmjs.com/package/jsonwebtoken. It appears to be tailored for NodeJS. Is it feasible to utilize this library in the browser? My attempts so far have resulted in the ...

Best practice for saving a User object to the Request in a Nest.js middleware

Currently, in my nest.js application, I have implemented a middleware to authenticate Firebase tokens and map the user_id to my database. Within this middleware, I retrieve the user_id from Firebase, fetch the corresponding User object from the database, a ...

Having trouble getting my Angular project up and running - facing issues with dependency tree resolution (ERESOLVE)

Currently, I am in the process of following an Angular tutorial and I wanted to run a project created by the instructor. To achieve this, I referred to the steps outlined in the 'how-to-use' file: How to use Begin by running "npm install" within ...

The functionality of the Ionic 4 app differs from that of an Electron app

I've encountered an issue with my Ionic 4 capacitor app. While it functions properly on Android studio, I'm having trouble getting it to work on Electron. Any ideas on how to resolve this? Here are the steps I took to convert it to Electron: np ...

Challenge when providing particular strings in Typescript

Something seems to be wrong with the str variable on line number 15. I would have expected the Typescript compiler to understand that str will only ever have the values 'foo' or 'bar' import { useEffect } from 'react' type Ty ...

Tips for creating an API URL request with two search terms using Angular and TypeScript

I have developed a MapQuest API application that includes two input boxes - one for the "from" location and another for the "to" location for navigation. Currently, I have hardcoded the values for these locations in my app.component file, which retrieves t ...

Using Typescript to retrieve the Return Type of a function when called with specific Parameter types

My goal is to create 2 interfaces for accessing the database: dao can be used by both admins and regular users, so each function needs an isAdmin:boolean parameter (e.g. updateUser(isAdmin: boolean, returnUser)) daoAsAdmin, on the other hand, allows metho ...

Incorporating a particular JavaScript library into Angular 4 (in case the library doesn't have a variable export)

I am attempting to display the difference between two JSON objects in an Angular 4 view. I have been using a library called angular-object-diff, which was originally created for AngularJS. You can view a demo of this library here: Link I have trie ...

Using Angular2, you can dynamically assign values to data-* attributes

In my project, I am looking to create a component that can display different icons based on input. The format required by the icon framework is as follows: <span class="icon icon-generic" data-icon="B"></span> The data-icon="B" attribute sp ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

Set the mat-option as active by marking it with a check symbol

Currently, I am utilizing mat-autocomplete. Whenever a selection is made manually from the dropdown options, the chosen item is displayed with a distinct background color and has a checkmark on the right side. However, when an option in the dropdown is se ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

How can I retrieve a password entered in a Material UI Textfield?

My code is functioning properly, but I would like to enhance it by adding an option for users to view the password they are typing. Is there a way to implement this feature? const [email, setEmail] = useState(''); const [password, setPassword] = ...

What is the best way to display the arrows on a sorted table based on the sorting order in Angular?

I need assistance with sorting a table either from largest to smallest or alphabetically. Here is the HTML code of the section I'm trying to sort: <tr> <th scope="col" [appSort]="dataList" data-order ...

"Enhance your forms with RadixUI's beautiful designs for

New to Radix UI and styling components, I encountered difficulties while trying to adapt a JSX component to Radix UI: Utilizing Radix UI Radio Groups, I aim to style my component similar to this example from Hyper UI with grid layout showing stacked conte ...

Angular Error - TS2322: The specified type of 'Object | null' cannot be assigned to 'NgIterable<any> | null | undefined'

I encountered an error in homes.component.html while trying to run my Angular project to showcase a list of homes from a JSON file. https://i.stack.imgur.com/D0vLQ.jpg Json File [ { "image_url": "https://images.unsplash.com/ph ...

Can TypeScript support passing named rest arguments within the type declaration?

Using Tuple types in TypeScript enables us to create typesafe rest arguments: type Params = [string,number,string] const fn = (...args: Params) => null // Type is (args_0: string, args_1: number, args_2: string) => null Is there a method to assign ...

Guide on defining a data type for the response payload in a Next.js route controller

interface DefaultResponse<T> { success: boolean; message?: string; user?: T; } export async function POST(req: Request) { const body: Pick<User, 'email' | 'password'> = await req.json(); const user = await prisma ...