Mocking TypeScript imports for Storybook

Viewed 13

I am attempting to mock the import of a module for use in Storybook but I can only do it with JavaScript and CJS imports, not TypeScript and ESM. My current webpackFinal contains this

config.resolve.alias['moduleToMock'] = require.resolve('../src/mocks/mockModule')
return config;

This current config doesn't work with TypeScript and will throw an error saying that the mock module can't be found. How can I configure this to work with TypeScript?

1 Answers

In general TypeScript only throws errors when you try to compile the code. If you encounter an error on code execution this is very likely more related to your code rewrite. If the webpackFinal of the Storybook already supports ESM and you need to import the module synchronously then you can create a replacement for the require function like this:

import { createRequire } from 'module'
const require = createRequire(import.meta.url)

...

config.resolve.alias['moduleToMock'] = require.resolve('../src/mocks/mockModule')

Hope it helps.

Related