Storybook - Cannot Mock a Nested React-Router-Dom Link without throwing endless NPM errors - javascript

I am trying to implement StorybookJS into a SSR React app. Basic components work fine (button, headers etc). But anything that nests using dependencies like react-router-dom breaks.
Example:
We have a custom built <Link /> component that manages external links with a ternary. The external links flip to <a href= while internals use react-router-dom's <Link> imported as <ReactLink />. That code is like this:
// src/client/components/link/Link.js
import { Link as ReactLink } from "react-router-dom";
import { isLinkExternal } from "services/utils";
export const Link = ({ href, children = null, ...props }) => {
return isLinkExternal(href) ? (
<a href={href} {...props}>
{children}
</a>
) : (
<ReactLink to={href} {...props}>
{children}
</ReactLink>
);
};
The StorybookJS file for it looks like this:-
// link.stories.js
import React from "react";
import { Link } from "./Link"; // importing my component
export default {
title: "My Components/Link",
component: Link, // assigning my component
};
export const MyStoryBookLink = () => <Link href="/foo">I am a link</Link>;
Now, when i run Storybook it throws a load of errors, here are the recurring/main ones:-
ERROR in ./node_modules/redis-parser/lib/hiredis.js
Module not found: Error: Can't resolve 'hiredis' in '/Users/me/Documents/my-proj/node_modules/redis-parser/lib'
...
...
# ./.storybook/generated-stories-entry.js
I haven't touched anything redis / hiredis related and there is no such file as generated-stories-entry.js. The app works perfectly in Dev and Production so this is exclusively a Storybook env issue.
Next error down:
ERROR in ./node_modules/cache-manager-ioredis/node_modules/ioredis/lib/connectors/connector.js
Module not found: Error: Can't resolve 'net' in '/Users/me/Documents/myProject/node_modules/cache-manager-ioredis/node_modules/ioredis/lib/connectors'
Again, Though we are using cache-manager-ioredis, no idea why this is suddenly missing a module if it works fine on the app itself and all i'm trying to do is render a .
Next one:
Module not found: Error: Can't resolve 'tls' in cache-manager-ioredis
Same thing again^^
Then i get a load of these:
/Users/me/Documents/myProj/__mocks__/hiredis doesn't exist
.mjs
/Users/me/Documents/myProj/__mocks__/hiredis.mjs doesn't exist
.js
/Users/me/Documents/myProj/__mocks__/hiredis.js doesn't exist
.jsx
/Users/me/Documents/myProj/__mocks__/hiredis.jsx doesn't exist
.ts
/Users/me/Documents/myProj/__mocks__/hiredis.ts doesn't exist
.tsx
/Users/me/Documents/myProj/__mocks__/hiredis.tsx doesn't exist
.json
/Users/me/Documents/myProj/__mocks__/hiredis.json doesn't exist
.cjs
/Users/me/Documents/myProj/__mocks__/hiredis.cjs doesn't exist
Suggests it's looking for mocks to cover these sub sub sub dependencies, wherever they're needed.
I get the same for net and tls.
Finally, I get some:
Field 'browser' doesn't contain a valid alias configuration
I'm thinking somewhere in the depths of using react-router-dom/Link it is trying to find these, and they would only be there if webpack dev server / hot reloading made them accessible, OR if they were transpiled to be accessible from the production bundle.
But how do I mock these out? And is there an easy way to do it rather than manually mocking every sub dependency?
I have tried:
adding __mocks__/react-router-dom.js with an export const Link = ({props}) => <div>{children}</div> but it doesnt seem to kick in.
adding alias logic to .storybook/main.js:
webpackFinal: (config) => {
config.resolve.alias['react-router-dom'] = require.resolve('../__mocks__/react-router-dom.js');
return config;
},
Again, nothing seems to change.
using the storybook-react-router pkg but this seems quite old now, it configs to an old config.js file rather than main.js and uses the older storiesOf syntax. Also couldn't get to do anything.
manually installed tls, hiredis etc as --save-dev dependencies. But this seems hack. Why are these modules missing?
I cannot believe Storybook is this hard to use, more likely I'm overlooking something. I just want to mock something as common and basic as a from RRD.
What am I doing wrong? What am I missing?

I think I found the reason. It is because of node.js packages. To make it work, there are 2 solutions.
avoid importing node.js packages (usually related to SSR) for storybook related code. I use NX to structure my code, so I can easily move those part to its own library and only reference it from the top. (No storybook for the top App either in this solution)
skip those packages in the config.
something like
config.resolve.fallback = { http: false, net: false, tls: false, fs: false, dns: false, path: false };

Related

How can I force Webpack in a Next.JS app to resolve to a specific dependency from an external directory?

Given the following directory structure, is it possible to have ALL react imports resolve to react-b?
|__node_modules
| |__react-a
|
|__app-a
| |__component-a
|
|__next-app
| |__react-b
| |__component-b
// component-a
import { useEffect } from 'react' // I need this to resolve to next-app/node_modules/react
export function() {
useEffect(() => {} , [])
return <></>
}
// component-b
import ComponentA from "../app-a/component-a"
export function() {
return <ComponentA />
}
The issue I am having is that we are migrating to a Next.JS app (next-app) but we want to continue to import components from (app-a). app-a is stuck for now on react 17.x.x but Next.JS is using 18.x.x. So when next-app is built, I need all react imports to resolve to react 18.x.x. At the time of writing this post we are using the experimental.externalDir setting to allow for importing components from outside the root of the next.js app.
The crux of it is that when importing from app-a I still need react to resolve to next-app/node_modules/react.
Webpack aliases seem to be the recommended answer generally but they don't appear to apply correctly in this situation.
I have solved this specific problem by using the next config transpilePackages list. Some dependencies that are dependent on react are causing the react version mismatch by importing react from the root node_modules. By including these packages in the transpilePackages list in the next config, it seems that next is pre-compiling these libs using the correct react version.
Example:
// next.config.js
const nextConfig = {
...other_config,
transpilePackages: ["react-focus-lock"],
}
Unfortunately I haven't fully appreciated why this imports the correct react dependency while using webpack resolve aliases does not.

Can't generate Nuxt website with #googlemaps/js-api-loader

I am using #googlemaps/js-api-loader in my Nuxt 3 website. Everything works fine in local development, but when I try to build the project with nuxt generate (no matter if locally or on Vercel) I'm getting following error:
[nuxt] [request error] Named export 'Loader' not found. The requested module 'file:///path/to/website/node_modules/#googlemaps/js-api-loader/dist/index.umd.js' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using:
The important part of loading script looks like this:
import { Loader } from '#googlemaps/js-api-loader';
const loader = new Loader({
apiKey: config.googleMapsApiKey,
version: 'weekly',
});
onMounted(async() => {
await loader
.load()
...
so I tried to import this package differently, e.g.:
import * as gmaps from '#googlemaps/js-api-loader';
const { Loader } = gmaps;
and the previous error disappeared, but now I'm getting
[Vue warn]: Unhandled error during execution of setup function
at <DynamicLocations class="contact__map" locations= [
{
id: 1,
...
[nuxt] [request error] gmaps.Loader is not a constructor
at setup (./.nuxt/prerender/chunks/app/server.mjs:5536:20)
at _sfc_main$t.setup (./.nuxt/prerender/chunks/app/server.mjs:5582:25)
at callWithErrorHandling (./.nuxt/prerender/chunks/renderer.mjs:2654:23)
at setupStatefulComponent (./.nuxt/prerender/chunks/renderer.mjs:9548:30)
at setupComponent (./.nuxt/prerender/chunks/renderer.mjs:9503:12)
at renderComponentVNode (./.nuxt/prerender/chunks/renderer.mjs:12068:17)
at Object.ssrRenderComponent (./.nuxt/prerender/chunks/renderer.mjs:12504:12)
at ./.nuxt/prerender/chunks/app/server.mjs:5628:36
at renderComponentSubTree (./.nuxt/prerender/chunks/renderer.mjs:12149:13)
at renderComponentVNode (./.nuxt/prerender/chunks/renderer.mjs:12084:16)
I also can't import package by default export. Do you have any ideas what's going on and how can I fix this?
I found a documentation page related to this problem and there is the following information:
If you encounter these errors, the issue is almost certainly with the upstream library. They need to fix their library to support being imported by Node.
Although they provide a solution to get rid of errors by adding the package to build.transpile:
build: {
transpile: ['#googlemaps/js-api-loader'],
},
It worked for me

Client-only Nuxt 3 Vue plugin

I am new to Nuxt and Vue, so go easy on me. I am trying to create a video player component in my Nuxt 3 app using vue3-video-player, which doesn't seem to support SSR based on the following error I get when I import it in my video component:
ReferenceError: navigator is not defined
This error persists even if the component is wrapped with <ClientOnly>. So, based on what I saw in the Nuxt 3 Documentation I thought I would create a client-only plugin located at plugins/vue3-video-player.client.js with the following contents:
import Vue3VideoPlayer from '#cloudgeek/vue3-video-player'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(Vue3VideoPlayer)
})
But when I try to use it in my component as <vue3-video-player>, I get the following error:
[Vue warn]: Failed to resolve component: vue3-video-player
So I guess my question is how do I create a client-only Vue component using Nuxt 3 plugins? Or is there an entirely different approach that would work better?
Solution for nuxt 3:
Nuxt will automatically read the files in your plugins directory and load them. You can use .server or .client suffix in the file name to load a plugin only on the server or client side.
For example:
plugins/apexcharts.client.ts
Everything is so simple! And that is why we love nuxt ❤️
Solution for nuxt 2 (to show the difference):
nuxt.config.ts
plugins: [
{src: '~/plugins/apexcharts', mode: 'client'}
],
This is only for nuxt 2 because All plugins in your nuxt 3 plugins/ directory are auto-registered, so you should not add them to your nuxt.config separately.
you could try to provide a helper function. As mentioned in the docs.
import Vue3VideoPlayer from '#cloudgeek/vue3-video-player'
export default defineNuxtPlugin((nuxtApp) => {
return {
provide: {
Vue3VideoPlayer
}
}
})
To tag along with the given correct answer here,
If you're trying to install and use a third party NPM package, and running into "window is not defined" type errors, you can load the package as a plugin as follows (eg WAD)
npm install web-audio-daw
// plugins/wad.client.ts
import Wad from "web-audio-daw"
export default defineNuxtPlugin(nuxtApp => {
return {
provide: {
Wad,
}
}
})
// pages/whatever.vue
<script lang="ts" setup>
const { $Wad } = useNuxtApp();
// Can use $Wad normally from here on out
</script>

Cypress not recognizing my imported module from outside /cypress directory

I am trying to import a module from a file outside my /cypress directory into the /cypress/integration directory's test.spec.js file like so:
import { LAB_MODEL } from '../../models/search/lab-model';
But inside this imported module "LAB_MODEL" there are other files being imported using the "##" at the start of the file imports like
import ExperimentDetails from "##/components/experiment/ExperimentDetails";
and I think this is why Cypress isn't working and giving me this error:
Error: Webpack Compilation Error
./models/search/lab-model.js
Module not found: Error: Can't resolve '##/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'
resolve '##/components/experiment/ExperimentDetails' in '/Users/hidden/models/search'
Parsed request is a module
using description file: /Users/hidden/package.json (relative path: ./models/search)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
So I think this is the reason why my test won't run, but I have no idea how to make Cypress recognize "##" imports and can't find any documentation/stackoverflow answers, any help is appreciated, thanks!
##/ looks like something that gets translated into a full path during the Nuxt build.
(ref The alias Property).
Cypress has a separate build that doesn't know about this Nuxt feature. You could try to replicate it with some webpack config via a preprocessor, but another way is to have your Nuxt app put a reference to lab_model on the window object
// somewhere in the Nuxt app
if (window.Cypress) {
window.lab_model = LAB_MODEL;
}
then at the top of the test
const lab_model = cy.state('window').lab_model;
This has the benefit of giving you the exact same instance of lab_model, in case you wanted to stub something.
In a starter Nuxt app, I added the code window.lab_model = LAB_MODEL in /pages/index.vue, but you can add it in any component that imports it, right after the import statement.
In the spec add a .should() to test the property exists, to allow the app time to settle.
it('gets labModel from the Nuxt app', () => {
cy.visit('http://localhost:3000/')
cy.window()
.should('have.property', 'lab_model') // retries until property appears
.then(labModel => {
console.log(labModel)
// test with labModel here
})
})

How to Embed StencilJS components inside Storybook React App?

I'm trying to integrate Stencil and Storybook inside the same project. I've been following this set up guide and this one however one of the steps is to publish the library of components to NPM and that's not what I want.
I have this repo which I've configured with components library (src folder) and with the reviewer of those components with Storybook, which resides in the storybook folder.
The problem is that when I compile the components using Stencil and copy the dist folder inside the Storybook app and import the component nothing renders. Tweaking the configuration using custom head tags I was able to import it correctly however no styles where applied.
When I open the network panel there is some error when importing the component:
And thus the component is present in the DOM but with visibility set to hidden, which I think it does when there is an error.
This is the component au-button:
import { Component } from '#stencil/core';
#Component({
tag: 'au-button',
styleUrl: 'button.css',
shadow: true
})
export class Button {
render() {
return (
<button class="test">Hello</button>
);
}
}
Here is the story my component:
import React from 'react';
import { storiesOf } from '#storybook/react';
import '../components/components.js'
storiesOf('Button', module)
.add('with text', () => <au-button></au-button>)
These are the scripts inside the Storybook app:
"scripts": {
"storybook": "start-storybook -p 9009",
"build-storybook": "build-storybook",
"copy": "cp -R ./../dist/* components"
},
And the workflow is as follows:
Launch storybook
Make changes in the component
Execute build command
Execute copy command
Also, I would like to automate the developer experience, but after I solve this problem first.
Any ideas of what I could be doing wrong?
Sample for this could be found in the repo
https://github.com/shanmugapriyaEK/stencil-storybook. It autogenerates stories with knobs and notes. Also it has custom theme in it. Hope it helps.
I'm using #storybook/polymer and it's working for me really well.
following your example:
import { Component } from '#stencil/core';
#Component({
tag: 'au-button',
styleUrl: 'button.css',
shadow: true
})
export class Button {
render() {
return (
<button class="test">Hello</button>
);
}
}
the story would be:
import { storiesOf } from '#storybook/polymer';
storiesOf('Button', module)
.add('with text', () => <au-button></au-button>)
the scripts in the package.json:
"scripts": {
"storybook": "start-storybook -p 9001 -c .storybook -s www"
},
the storybook config file:
import { configure, addDecorator } from '#storybook/polymer';
const req = require.context('../src', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach((filename) => req(filename))
}
configure(loadStories, module);
and storybook preview-head.html you have to add to the body the following:
<body>
<div id="root"></div>
<div id="error-message"></div>
<div id="error-stack"></div>
</body>
I've been following this set up guide and this one however one of the steps is to publish the library of components to NPM and that's not what I want.
My reading of those guides is that they're stating “publish to NPM” as a way to have your files at a known URL, that will work most easily for deployment.
Without doing that, you'll need to figure out a different deployment strategy. How will you get the build products – the dist directory and static files – published so that your HTML will be able to reference it at a known URL? By choosing to diverge from the guidelines, that's the problem you have to address manually instead.
Not an insurmountable problem, but there is no general solution for all. You've chosen (for your own reasons) to reject the solution offered by the how-to guides, which means you accept the mantle of “I know what I want” instead :-)

Categories