Switching Storybook from Webpack to Vita in Gatsby app - vite

I work on a Gatsby project and I'm hoping to run our Storybook with Vita instead of our existing Webpack setup. I'm clearly not doing it right.
I added the plugins:
"#storybook/builder-vite": "^0.4.2",
"#vitejs/plugin-react": "^3.1.0",
"vite": "^4.1.1",
I also added our aliases by importing my tsconfigand converting the paths to the right format.
Although most of my attempts to run it resulted in about 1000 instances of
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
it's actually running now. And it booted up WAY faster than it used to.
The only issue appears to be that it's not reloading, not at all. I make a change in a component, or a change in a story, and there is zero output in the terminal running storybook.
Although I do notice that this run, although it looks like it's working in the browser, does still give only these two errors:
Failed to resolve dependency: react/jsx-runtime, present in 'optimizeDeps.include'
Failed to resolve dependency: react/jsx-dev-runtime, present in 'optimizeDeps.include'
How can I fix this? I'm so close!
I've tried...
const react = require('#vitejs/plugin-react');
//...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
// is this where this goes?
plugins: [
react({
jsxRuntime: 'classic',
}),
],
resolve: { alias: aliasPathsVite },
},
})
},
}
Which does open Storybook in the browser, but it doesn't load, and the terminal gives endless instances of:
10:30:38 AM [vite] Internal server error: Transform failed with 2 errors:
Typography/Links.tsx:3:4: ERROR: The symbol "prevRefreshReg" has already been declared
Typography/Links.tsx:4:4: ERROR: The symbol "prevRefreshSig" has already been declared
Plugin: vite:esbuild
File: Typography/Links.tsx:1:42
The symbol "prevRefreshReg" has already been declared
1 | import RefreshRuntime from "/#react-refresh";let prevRefreshReg;let prevRefreshSig;if (import.meta.hot) { if (!window.__vite_plugin_react_preamble_installed__) { throw new Error( "#vitejs/plugin-react can't detect preamble. Something is wrong. " + "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201" ); } prevRefreshReg = window.$RefreshReg$; prevRefreshSig = window.$RefreshSig$; window.$RefreshReg$ = (type, id) => { RefreshRuntime.register(type, "Typography/Links.tsx" + " " + id) }; window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;}var _jsxFileName = "Typography/Links.tsx";
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
| ^
4 | let prevRefreshSig;
5 | if (import.meta.hot) {
The symbol "prevRefreshSig" has already been declared
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
4 | let prevRefreshSig;
| ^
5 | if (import.meta.hot) {
6 | if (!window.__vite_plugin_react_preamble_installed__) {
at failureErrorWithLog (node_modules/esbuild/lib/main.js:1604:15)
at node_modules/esbuild/lib/main.js:837:29
at responseCallbacks.<computed> (node_modules/esbuild/lib/main.js:701:9)
at handleIncomingPacket (node_modules/esbuild/lib/main.js:756:9)
at Socket.readFromStdout (node_modules/esbuild/lib/main.js:677:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)
I've tried...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
resolve: {
alias: {
...aliasPathsVite,
'react/jsx-runtime': path.join(
__dirname,
'node-modules/react/jsx-runtime'
),
},
optimizeDeps: {
include: ['react/jsx-runtime']
}
},
})
},
}
which opens a non-working Storybook in the browser, and the terminal says this hundreds of times
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
Then some of these:
[vite] error while updating dependencies:
Error: ENOENT: no such file or directory, rename 'node_modules/.vite-storybook/deps_temp' -> 'node_modules/.vite-storybook/deps'
at renameSync (node:fs:1030:3)
at Object.commit (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42874:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async commitProcessing (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42348:17)
at async runOptimizer (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42386:17)
And then a bunch of issues importing CSS files, like this one
10:45:29 AM [vite] Internal server error: Failed to resolve import "./header.css" from "node_modules/#storybook/mdx1-csf/dist/esm/stories/Header.js?v=ec48b265". Does the file exist?

Have you tried something like this?
resolve: {
alias: {
'react/jsx-runtime': 'react/jsx-runtime.js',
},
},
Source: https://github.com/vitejs/vite/issues/6215
Also:
optimizeDeps.include: ['react/jsx-runtime']
Another way can be tweaking the configuration of #vitejs/plugin-react:
import react from '#vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
jsxRuntime: 'classic',
}),
]
});

Related

Is There a way to get the full path of file dependencies in Madge API?

I'm using Magde API (https://github.com/pahen/madge/blob/master/README.md) to generate the dependency graph of my JS file...
Once the dependencies are return as object, the file paths are not clearly documented... I was wondering if there exists a way to tell Madge to specify the full path not the cut it
I want to get the dependencies of this file:
import * as t from 'C:/Users/Tec/todolist_example_jest/req2.js';
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
As we can see there exists a dependency on this file:
'C:/Users/Tec/todolist_example_jest/req2.js'; But when using madge to get the dependencies ... look below to see what is the output
Here is the code snippet:
madge('file path').then((res) => {
dependencies = res.obj(); // the dependencies as an object
console.log(dependencies);
});
and this is the output:
{
'../../../../todolist_example_jest/req2.js': [],
'simpleElement.jsx': [ '../../../../todolist_example_jest/req2.js' ]
}
../../../../todolist_example_jest/req2.js
node:fs:585
handleErrorFromBinding(ctx);
^
Error: ENOENT: no such file or directory, open '../../../../todolist_example_jest/req2.js'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at C:\Users\Tec\React Native Applications\Upload-main\backend\app.js:47:27
at Array.forEach (<anonymous>)
at C:\Users\Tec\React Native Applications\Upload-main\backend\app.js:44:33 {
errno: -4058,
syscall: 'open',
code: 'ENOENT',
path: '../../../../todolist_example_jest/req2.js'
}

Turborepo: SyntaxError: Cannot use import statement outside a module

This is the complete error I get:
cache bypass, force executing 35a9a396ec0cc67c
$ jest --verbose
FAIL __test__/Krebit.test.ts
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/Users/andres/Work/krebit-work/krebit/node_modules/#glazed/datamodel/dist/index.js:41
import { TileLoader } from '#glazed/tile-loader';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { ethers } from 'ethers';
2 | import { CeramicClient } from '#ceramicnetwork/http-client';
> 3 | import { DataModel } from '#glazed/datamodel';
| ^
4 | import { DIDDataStore } from '#glazed/did-datastore';
5 |
6 | // DID-session
at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (src/lib/ceramic.ts:3:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.909 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ERROR: command finished with error: command (packages/reputation-passport) yarn run test exited (1)
I have already installed the following packages and added this config:
Packages:
#types/jest: ^28.1.6
jest: ^28.1.3
ts-jest: ^28.0.7
Configuration for jest:
module.exports = {
testEnvironment: 'node',
preset: 'ts-jest',
testMatch: null,
testRegex: '/__test__/.*\\.test\\.(js|ts)$',
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/out/'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'],
clearMocks: true,
globals: {
'ts-jest': {
tsconfig: '<rootDir>/__test__/tsconfig.json',
diagnostics: false
}
}
};
The test I'm implementing is as simple as:
import { ethers } from 'ethers';
import Krebit from '../src';
describe('Krebit Class', () => {
let wallet: ethers.Wallet;
let ethProvider: ethers.providers.Provider;
beforeAll(async () => {
ethProvider = Krebit.lib.ethereum.getProvider();
const pKey = ethers.Wallet.createRandom();
wallet = new ethers.Wallet(pKey, ethProvider);
});
test('The user should be able to connect with her Wallet, EthProvider, and Address', async () => {
console.log(wallet, ethProvider);
});
});
So, I guess the problem comes from the line: ethProvider = Krebit.lib.ethereum.getProvider();, which is importing the package I want to test... If someone needs to read this code, I can share it too...

Mirage/Pretender causes errors in Vitest

I'm working on migrating from Jest to Vitest (alongside CRA > Vite migration), and I think I've got everything working, except that using Mirage causes errors. Setting the vite config test environment between happy-dom and 'jsdom' both give different errors, though they appear to be related or similar or the same (just with happy-dom giving much more useful information!
My very simplified test:
import { describe, expect, it } from "vitest"
import { createServer } from "miragejs";
describe('tests', () => {
createServer({})
it('works', () => {
expect(true).toEqual(true)
})
})
happydom error
TypeError: Cannot read properties of undefined (reading 'prototype')
❯ interceptor node_modules/pretender/dist/pretender.js:1540:46
❯ new Pretender node_modules/pretender/dist/pretender.js:1638:32
❯ PretenderConfig._create node_modules/miragejs/dist/mirage-cjs.js:6398:14
❯ PretenderConfig.create node_modules/miragejs/dist/mirage-cjs.js:6259:27
❯ Server.config node_modules/miragejs/dist/mirage-cjs.js:6824:24
❯ new Server node_modules/miragejs/dist/mirage-cjs.js:6760:10
❯ Proxy.createServer node_modules/miragejs/dist/mirage-cjs.js:6725:10
❯ src/test.test.tsx:5:2
3|
4| describe('tests', () => {
5| createServer({})
| ^
6| it('works', () => {
7| expect(true).toEqual(true)
jsdom error
Error: Errors occurred while running tests. For more information, see serialized error.
❯ Object.runTests node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:7048:17
❯ processTicksAndRejections node:internal/process/task_queues:96:5
❯ async file:/Users/jtuzman-superdraft/dev/superdraft-core-admin/NEW-vite-admin/node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10545:9
❯ Vitest.runFiles node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10558:12
❯ Vitest.start node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:10479:5
❯ startVitest node_modules/vitest/dist/chunk-vite-node-externalize.6956d2d9.mjs:11204:5
❯ start node_modules/vitest/dist/cli.mjs:666:9
❯ CAC.run node_modules/vitest/dist/cli.mjs:662:3
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: {
"errors": [
[Error: Internal error: Error constructor is not present on the given global object.],
],
}
vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react'
import svgrPlugin from 'vite-plugin-svgr';
import macrosPlugin from "vite-plugin-babel-macros"
import checker from 'vite-plugin-checker'
// https://vitejs.dev/config/
export default defineConfig({
test: {
globals: true,
environment: "jsdom", // or "happy-dom"
},
define: {
global: {},
},
esbuild: {
logOverride: { 'this-is-undefined-in-esm': 'silent' }
},
plugins: [
react(),
svgrPlugin({
svgrOptions: {
icon: true,
},
}),
macrosPlugin(),
checker({
typescript: true,
overlay: {
panelStyle: 'height: 100vh; max-height: unset;'
}
})
],
});
This GitHub issue appears to deal with the same question but doesn't appear to solve it.
Ran into the same thing. It's the global: {} statement. When I commented it out in my vite.config.ts file, my tests ran successfully. I haven't figured out another way to solve the global error yet that caused me to set that in the first place though.
happy-dom does not provide an implementation for XMLHttpRequest, which is used by pretenderjs. The most straightforward walk around is to put the following line at the very top of your test code, before the the vitest environment:
this.XMLHttpRequest = vi.fn()
//#vitest-environment happy-dom

Vite with Jest: cannot find module start with alias '#'

I'm using Jest in Vite. It works until I import a module from node_module.
import { defineComponent } from 'vue'
import { useCookies } from '#vueuse/integrations/useCookies'
I got this error.
FAIL src/components/MyComponent/index.test.ts
● Test suite failed to run
Cannot find module '#vueuse/integrations/useCookies' from 'src/components/MyComponent/index.vue'
Require stack:
src/components/MyComponent/index.vue
src/components/MyComponent/index.test.ts
16 | <script lang="ts">
17 | import { defineComponent } from 'vue'
> 18 | import { useCookies } from '#vueuse/integrations/useCookies'
| ^
19 |
20 | export default defineComponent({
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
I guess somehow Jest cannot resolve the module starts with '#'. Maybe I should write a moduleNameMapper? I also tried to install vite-jest, but somehow my app just crash, maybe I mess up something.
Anyway, thanks for your time, and if you need more information like my jest.config.js or vite.config.ts, please let me know.
Thank you.
Use moduleNameMapper in your jest.config.js file like following:
module.exports = {
//...
moduleNameMapper: {
"^#/(.*)$": "<rootDir>/src/$1",
},
};
Also, if you are using TypeScript, you should add the following to your tsconfig.json file as well:
{
"compilerOptions": {
"paths": {
"#/*": ["./src"]
}
}
}

Error when trying to use CanvasJS via RequireJS

I'm trying to use CanvasJS inside my project. I'm using RequireJS to manage the modules, and have this in the main script:
define(['domReady',"canvasjs","common-functions"], function(domReady,CanvasJS) {
domReady(function () {
window.CanvasJS = CanvasJS;
init_page_select();
});
});
This is what I have in my requireJS config file for the path:
"paths": {
// other stuff here
"canvasjs": "node_modules/canvasjs/dist/canvasjs.min"
},
I can see the canvasjs.min.js file being grabbed fine - but then I get this weird error:
ReferenceError: intToHexColorString is not defined[Learn More] canvasjs.min.js:7:7042
[33]</n.prototype.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:7:7042
[28]</n.prototype.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:5:14150
n/this.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:8:17771
init_page_select https://www.test.org/2018/js/lib/spot_view_stats.js:83:2
<anonymous> https://www.test.org/2018/js/lib/spot_view_stats.js:4:3
domReady https://www.test.org/2018/js/lib/domready.js:105:13
<anonymous> https://www.test.org/2018/js/lib/spot_view_stats.js:2:2
execCb https://www.test.org/2018/js/lib/require.js:5:12859
check https://www.test.org/2018/js/lib/require.js:5:6575
enable/</< https://www.test.org/2018/js/lib/require.js:5:9031
bind/< https://www.test.org/2018/js/lib/require.js:5:812
emit/< https://www.test.org/2018/js/lib/require.js:5:9497
each https://www.test.org/2018/js/lib/require.js:5:289
emit https://www.test.org/2018/js/lib/require.js:5:9465
check https://www.test.org/2018/js/lib/require.js:5:7169
enable/</< https://www.test.org/2018/js/lib/require.js:5:9031
bind/< https://www.test.org/2018/js/lib/require.js:5:812
emit/< https://www.test.org/2018/js/lib/require.js:5:9497
each https://www.test.org/2018/js/lib/require.js:5:289
emit https://www.test.org/2018/js/lib/require.js:5:9465
check https://www.test.org/2018/js/lib/require.js:5:7169
enable https://www.test.org/2018/js/lib/require.js:5:9358
init https://www.test.org/2018/js/lib/require.js:5:5716
h https://www.test.org/2018/js/lib/require.js:5:4287
completeLoad https://www.test.org/2018/js/lib/require.js:5:12090
onScriptLoad https://www.test.org/2018/js/lib/require.js:5:13014
I'm invoking it with:
var chart = new CanvasJS.Chart("thegraph",
{
title:{
text: impressionText
},
theme: "theme2",
axisX: {
valueFormatString: "MMM-DD-YYYY",
labelAngle: -50
},
axisY:{
valueFormatString: "#0",
title: impressionText
},
data: [
{
type: "line",
showInLegend: true,
legendText: legendText,
dataPoints: dataPoints
}
]
});
chart.render();
Interestingly, if I tell it to load canvasjs.js instead of canvasjs.min.js, I get another error:
ReferenceError: intToHexColorString is not defined[Learn More]
OK so the problem seemed to be my version. For some reason "npm install canvasjs" was installing 1.8.1, but 2.2 was out. As per their request, I updated it to 2.2 and it sorted the problem. It seems weird npm is running such an outdated version though

Resources