Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook.

How can I set up Webpack so that I am able to import from another .storybook.ts file within a .storybook.ts?

Encountering an error message:

ERROR in ./src/components/Button/Button.stories.ts
Module not found: Error: Can't resolve '../Icon/Icon.stories'
in '/Users/dude/monorepo/frontend/storybook/src/components/Button'

The import causing the issue is:

import AppButton from './Button.vue';
import { iconPackOptions, iconPackDefaultValue } from '../Icon/Icon.stories';

The content of the file src/components/Icon/Icon.stories.ts looks like this:

import { storiesOf } from '@storybook/vue';
import { withKnobs, text, select } from '@storybook/addon-knobs';

import AppIcon from './Icon.vue';

// Knobs grouping
const groupId01 = 'icon';

// Icon Pack
export const iconPackOptions = {
  None: false,
  FontAwesomeProRegular: 'far',
  FontAwesomeFreeBrands: 'fab'
};
export const iconPackDefaultValue = iconPackOptions.FontAwesomeProRegular;

The contents of ./.storybook/webpack.config.js file are as follows:

const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const path = require('path');

module.exports = async ({ config }) => {

  config.module.rules.push({
    test: /\.css$/,
    loaders: ['style-loader', 'css-loader', 'postcss-loader'],
    include: path.resolve(__dirname, '../'),
  });

  config.module.rules.push({
    test: /\.scss$/,
    use: ['style-loader', 'css-loader', 'sass-loader'],
    include: path.resolve(__dirname, '../assets/styles')
  });

  config.resolve = {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      vue$: 'vue/dist/vue.esm.js',
      'assets': path.resolve('../src/assets'),
      '@': path.join(__dirname, '../src'),
    }
  };

  config.module.rules.push({
    test: /\.ts$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'ts-loader',
        options: {
          appendTsSuffixTo: [/\.vue$/],
          transpileOnly: true
        },
      }
    ]
  });

  config.plugins.push(new ForkTsCheckerWebpackPlugin());

  return config;
};

The content of ./.storybook/config.js file includes:

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

import '../src/plugins';
import '../src/assets/styles/main.scss';

const req = require.context('../src/components', true, /.stories.ts$/);
function loadStories() {
  req.keys().forEach(filename => req(filename));
}

configure(loadStories, module);

Answer №1

This configuration for the .storybook/webpack.config.js file is currently effective for me, especially when combined with the storysource addon. In case you do not require the storysource feature, simply eliminate the loader object by removing

@storybook/addon-storysource/loader
:

const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const path = require('path');

module.exports = async ({ config }) => {

  config.module.rules.push({
    test: /\.css$/,
    loaders: ['style-loader', 'css-loader', 'postcss-loader'],
    include: path.resolve(__dirname, '../'),
  });

  config.module.rules.push({
    test: /\.scss$/,
    use: ['style-loader', 'css-loader', 'sass-loader'],
    include: path.resolve(__dirname, '../assets/styles')
  });

  config.resolve = {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      vue$: 'vue/dist/vue.esm.js',
      'assets': path.resolve('../src/assets'),
      '@': path.join(__dirname, '../src'),
    }
  };

  config.module.rules.push({
    test: /\.stories\.ts?$/,
    exclude: /node_modules/,
    use: [
      {
        loader: require.resolve('babel-loader')
      },
      {
        loader: require.resolve('@storybook/addon-storysource/loader')
      }
    ]
  });

  config.module.rules.push({
    test: /\.ts$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'ts-loader',
        options: {
          appendTsSuffixTo: [/\.vue$/],
          transpileOnly: true
        },
      }
    ]
  });

  config.plugins.push(new ForkTsCheckerWebpackPlugin());

  return config;
};

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

Tips for implementing a custom form validation rule using a function parameter

I am currently in need of developing a rule for a form field that will allow me to compare the value entered in that particular field with multiple elements stored in an array. Below is a snippet of what I have so far: <template> <v-form v-model ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

Exploring the world of Node.js with fs, path, and the

I am facing an issue with the readdirSync function in my application. I need to access a specific folder located at the root of my app. development --allure ----allure-result --myapproot ----myapp.js The folder I want to read is allure-results, and to d ...

Passing variables to the ajax.done() function from within a loop - what you need to know

How can I pass a variable to the .done() method of an ajax call that is inside a loop? The code snippet below shows my initial attempt: <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </ ...

Creating the upcoming application without @react-google-maps/api is simply not possible

After incorporating a map from the documentation into my component, everything seemed to be functioning correctly in the development version. However, when attempting to build the project, an error arose: Type error: 'GoogleMap' cannot be used as ...

Real-time update of quiz results based on varying factors

In my quiz, I have set up variables that start at 0 and increase based on certain conditions. One variable should increase when a question is answered correctly, while the other should increase when a question is answered incorrectly. If you answer a quest ...

Sending JSON data results

I received this JSON response: {"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales of Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_ ...

Implement Vue router (version 4) in a vanilla .js file within the Quasar framework (version 2) for seamless navigation and

I'm attempting to access the router from a plain .js file within a Quasar project but I am encountering difficulties. In my search on how to achieve this in Vue, I found that people typically import the Router object from /src/router/index, like so: i ...

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

What are the limitations of using a JS file within an Angular application?

I am struggling to integrate some js methods from a file into an angular application. Unfortunately, the browser is unable to recognize the js file. I have tried following the guidelines in this SO post, but the browser still cannot locate the file in the ...

Is it possible to use multiple AJAX requests to automatically fill out form fields?

In my Backbone.js web application, there is a form with multiple dropdowns that need to be populated with data fetched from an API. Since all the application logic resides on the client side due to using Backbone.js, I want to avoid populating these dropd ...

Having trouble initiating the server using npm start

Just starting out with nodeJs: I have created a server.js file and installed nodejs. However, when I try to run "npm start", I encounter the following errors. C:\Users\server\server.js:43 if (!(req.headers &amp;& req.headers. ...

Effortless Hydration and Efficient Code Splitting in NextJS Application

I understand Lazy Hydration and Code Splitting, but how can I ensure that the split chunk is only downloaded when the component is being hydrated? This is what my code currently looks like import React from 'react'; import dynamic from 'nex ...

Issues arise when jQuery functions do not execute as expected within an "if" statement following

Recently, I delved into the realm of AJAX and embarked on a journey to learn its intricacies. Prior to seeking assistance here, I diligently scoured through past queries, such as this, but to no avail. Here is an excerpt from my code: $('.del'). ...

I'm curious, which redux architecture would you recommend for this specific scenario?

I'm currently developing an application and I'm facing a challenge in implementing Redux effectively in this particular scenario. Unfortunately, due to restrictions at my workplace, normalizing data is not an option. Let's consider the foll ...

Nuxt's fetchUser Auth function lacks reactivity and necessitates a manual refresh for updates to take effect

Working with Nuxt 2.15.3 and a Rails backend. I am currently in the process of implementing a Google OAuth workflow in my application, but I have encountered some difficulties with the steps following the retrieval of the access code. After the user succe ...

The compiler error TS2304 is indicating that it cannot locate the declaration for the term 'OnInit'

I successfully completed the Angular superhero tutorial and everything was functioning properly. However, when I close the CMD window running NPM and then reopen a new CMD window to reissue the NPM START command, I encounter two errors: src/app/DashBoard ...

Indicator malfunctioning on Carousel feature

I created a carousel containing six photos, but I am encountering an issue with the carousel indicators below. The first three indicators work correctly – when clicked, they take me to the corresponding slide (e.g., clicking the 1st indicator takes me ...

Dynamic CSS Changes in AngularJS Animations

I am currently working on a multi-stage web form using AngularJS. You can see an example of this form in action by visiting the link below: http://codepen.io/kwakwak/full/kvEig When clicking the "Next" button, the form slides to the right smoothly. Howev ...

Is there a way to match a compressed javascript stack trace with a source map to pinpoint the correct error message?

When managing our production server, I have implemented minified javascript without including a map file to prevent users from easily deciphering errors. To handle angular exceptions caught by $exceptionHandler, I developed a logging service that forwards ...