Storybook SyntaxError in preview.js - javascript

I have a React project where I want to start using Storybook. The initial basic configuration works correctly, even using JSX in the stories, but when I try to add a global decorator using JSX I get the following syntax error:
// .storybook/preview.js
import React from 'react';
export const decorators = [
(Story) => (
<div style={{ margin: '3em' }}>
<Story />
</div>
),
];
ERROR in ./.storybook/preview.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /home/user/Documents/react-test/.storybook/preview.jsx: Unexpected token, expected "," (5:11)
3 | export const decorators = [
4 | (Story) => (
> 5 | <div style={{ margin: '3em' }}>
| ^
6 | <Story />
7 | </div>
8 | ),
at Object._raise (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:776:17)
at Object.raiseWithData (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:769:17)
at Object.raise (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:737:17)
at Object.unexpected (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:9735:16)
at Object.expect (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:9721:28)
at Object.tsParseDelimitedListWorker (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:5557:14)
at Object.tsParseDelimitedList (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:5529:25)
at Object.tsParseBracketedList (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:5575:25)
at Object.tsParseTypeParameters (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:5684:24)
at /home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:7391:29
at Object.tryParse (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:9762:20)
at Object.parseMaybeAssign (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:7388:24)
at /home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:10427:39
at Object.allowInAnd (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:12104:12)
at Object.parseMaybeAssignAllowIn (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:10427:17)
at Object.parseParenAndDistinguishExpression (/home/user/Documents/react-test/node_modules/#babel/core/node_modules/#babel/parser/lib/index.js:11308:28)
# ./.storybook/preview.jsx-generated-config-entry.js 9:37-128
# multi ./node_modules/#storybook/core-client/dist/esm/globals/polyfills.js ./node_modules/#storybook/core-client/dist/esm/globals/globals.js ./.storybook/storybook-init-framework-entry.js ./node_modules/#storybook/addon-docs/dist/esm/frameworks/common/config.js-generated-other-entry.js ./node_modules/#storybook/addon-docs/dist/esm/frameworks/react/config.js-generated-other-entry.js ./node_modules/storybook-addon-gatsby/dist/preview.mjs-generated-other-entry.js ./node_modules/#storybook/addon-links/dist/esm/preset/addDecorator.js-generated-other-entry.js ./node_modules/#storybook/addon-actions/dist/esm/preset/addDecorator.js-generated-other-entry.js ./node_modules/#storybook/addon-actions/dist/esm/preset/addArgs.js-generated-other-entry.js ./node_modules/#storybook/addon-backgrounds/dist/esm/preset/addDecorator.js-generated-other-entry.js ./node_modules/#storybook/addon-backgrounds/dist/esm/preset/addParameter.js-generated-other-entry.js ./node_modules/#storybook/addon-measure/dist/esm/preset/preview.js-generated-other-entry.js ./node_modules/storybook-addon-outline/dist/esm/preset/addDecorator.js-generated-other-entry.js ./.storybook/preview.jsx-generated-config-entry.js ./.storybook/generated-stories-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined
What is missing here? I would be happy to provide more config files if needed.

Related

react dropzone with image preview written typescript

I am new to front end and typescript. I would like to create the ability to preview drag and drop files using react-dropzone, an example javascript version exists but does not work in typescript. I have run the following code.
import { useEffect, useCallback, useMemo, useState } from 'react';
import { useDropzone, FileWithPath, DropzoneState } from 'react-dropzone';
const styleDiv = {
margin: "1%"
}
const style = {
width: 200,
height: 150,
border: "1px dotted #888"
};
function App() {
const [files, setFiles] = useState([]);
const {getRootProps, getInputProps} = useDropzone({
accept: {
'image/*': []
},
onDrop: acceptedFiles => {
setFiles(acceptedFiles.map(file => Object.assign(file, {
preview: URL.createObjectURL(file)
})));
}
});
const thumbs = files.map(file => (
<div key={file.name}>
<div>
<img
src={file.preview}
// Revoke data uri after image is loaded
onLoad={() => { URL.revokeObjectURL(file.preview) }}
/>
</div>
</div>
));
useEffect(() => {
// Make sure to revoke the data uris to avoid memory leaks, will run on unmount
return () => files.forEach(file => URL.revokeObjectURL(file.preview));
}, []);
return (
<section className="container">
<div {...getRootProps({className: 'dropzone'})}>
<input {...getInputProps()} />
<p>Drag 'n' drop some files here, or click to select files</p>
</div>
<aside>
{thumbs}
</aside>
</section>
);
}
export default App;
I received the following error
Compiled with warnings.
[eslint]
src/App.tsx
Line 1:21: 'useCallback' is defined but never used #typescript-eslint/no-unused-vars
Line 1:34: 'useMemo' is defined but never used #typescript-eslint/no-unused-vars
Line 2:23: 'FileWithPath' is defined but never used #typescript-eslint/no-unused-vars
Line 2:37: 'DropzoneState' is defined but never used #typescript-eslint/no-unused-vars
Line 4:7: 'styleDiv' is assigned a value but never used #typescript-eslint/no-unused-vars
Line 8:7: 'style' is assigned a value but never used #typescript-eslint/no-unused-vars
Line 30:9: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images jsx-a11y/alt-text
Line 42:6: React Hook useEffect has a missing dependency: 'files'. Either include it or remove the dependency array react-hooks/exhaustive-deps
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
WARNING in [eslint]
src/App.tsx
Line 1:21: 'useCallback' is defined but never used #typescript-eslint/no-unused-vars
Line 1:34: 'useMemo' is defined but never used #typescript-eslint/no-unused-vars
Line 2:23: 'FileWithPath' is defined but never used #typescript-eslint/no-unused-vars
Line 2:37: 'DropzoneState' is defined but never used #typescript-eslint/no-unused-vars
Line 4:7: 'styleDiv' is assigned a value but never used #typescript-eslint/no-unused-vars
Line 8:7: 'style' is assigned a value but never used #typescript-eslint/no-unused-vars
Line 30:9: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images jsx-a11y/alt-text
Line 42:6: React Hook useEffect has a missing dependency: 'files'. Either include it or remove the dependency array react-hooks/exhaustive-deps
webpack compiled with 1 warning
ERROR in src/App.tsx:21:16
TS2345: Argument of type '(T & { preview: string; })[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type '(T & { preview: string; })[]' is not assignable to type 'never[]'.
Type 'T & { preview: string; }' is not assignable to type 'never'.
19 | },
20 | onDrop: acceptedFiles => {
> 21 | setFiles(acceptedFiles.map(file => Object.assign(file, {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> 22 | preview: URL.createObjectURL(file)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> 23 | })));
| ^^^^^^^^^^
24 | }
25 | });
26 |
ERROR in src/App.tsx:28:20
TS2339: Property 'name' does not exist on type 'never'.
26 |
27 | const thumbs = files.map(file => (
> 28 | <div key={file.name}>
| ^^^^
29 | <div>
30 | <img
31 | src={file.preview}
ERROR in src/App.tsx:31:21
TS2339: Property 'preview' does not exist on type 'never'.
29 | <div>
30 | <img
> 31 | src={file.preview}
| ^^^^^^^
32 | // Revoke data uri after image is loaded
33 | onLoad={() => { URL.revokeObjectURL(file.preview) }}
34 | />
ERROR in src/App.tsx:33:52
TS2339: Property 'preview' does not exist on type 'never'.
31 | src={file.preview}
32 | // Revoke data uri after image is loaded
> 33 | onLoad={() => { URL.revokeObjectURL(file.preview) }}
| ^^^^^^^
34 | />
35 | </div>
36 | </div>
ERROR in src/App.tsx:41:65
TS2339: Property 'preview' does not exist on type 'never'.
39 | useEffect(() => {
40 | // Make sure to revoke the data uris to avoid memory leaks, will run on unmount
> 41 | return () => files.forEach(file => URL.revokeObjectURL(file.preview));
| ^^^^^^^
42 | }, []);
43 |
44 | return (
I think the problem is that you are trying to access an object that does not exist, but I don't know how to solve it.
I would like to know how to solve this problem.
Modify your files state like this:
const [files, setFiles] = useState<(File & {preview:string})[]>([]);

Cannot import images from a sibling directory - React Native

I have tried many ways to get out of this problem.
I have a folder named Screens in which I have a file name HomeScreen.js
assets--
|__ padlock.png
Screens--
|__ HomeScreen.js
When I am trying to import padlock.png into HomeScreen.js it gives following error.
Unable to resolve module ./assets/padlock.png from D:\User\react\myproject\Screens\HomeScreen.js:
Following methods I have tried in HomeScreen.js
const imageLock = require("../assets/padlock.png"); //Not working
const imageLock = { uri: "../assets/padlock.png" }; //Not Working
import imageLock from "../assets/padlock.png"; //not working
I have make sure that padlock.png exist and I am not making any mistakes. Full error message is as below.
Unable to resolve module ./assets/padlock.png from D:\User\react\myproject\Screens\HomeScreen.js:
None of these files exist:
padlock.png
Screens\assets\padlock.png\index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
27 | const imageLock = require("../assets/padlock.png");
| ^
28 |
29 | export default function HomeScreen({ navigation }) {
30 | const [modalOpen, setModalOpen] = useState(false);
Did you try
<Image
style={{ width: 100, height: 100 }}
source={require('../assets/padlock.png')}
/>

How to dynamically import React JSX Component; SyntaxError: Unexpected Token

How can I dynamically import a file containing JSX and have it be transpiled like a regular import?
I'm trying to dynamically import() this React component:
import React from 'react';
export default () => {
return (
<div>Test</div>
);
}
from a service in my application:
import('./test').then(({default: Component}) => {
callback(Component);
});
but it appears the dynamic import doesn't transpile the JSX:
SyntaxError: /path/to/test.js: Unexpected token (5:4)
3 | export default () => {
4 | return (
5 | <div>Test</div>
| ^
6 | );
7 | }
8 |
I have plenty of regular imports which work fine:
import OtherComponent from './OtherComponent';
export default () => (
<OtherComponent />
);
so Babel is definitely transpiling those... just not the dynamic ones.
Looking at the build output from yarn build, I can see a chunk is created but it simply contains this error (implying the file cannot be transpiled at build time ?!?):
(window["webpackJsonptest-app"]=window["webpackJsonptest-app"]||[]).push([[0],{272:function(m,e){throw new Error('Module build failed (from ./node_modules/babel-loader/lib/index.js):\nSyntaxError: /path/to/build/test.js: Unexpected token (12:2) ... etc

node-vibrant package and react

People,
I´m trying to show the hex of a color inside a react Component with node-vibrant. (I have this node package installed)
It´s working when I run it with node from the console.
|- file.js
|- image.jpg
file.js
// I cannot make it work with ES6 importing
const Vibrant = require('node-vibrant');
let v = new Vibrant('image.jpg')
v.getPalette((err, palette) => console.log(palette.Vibrant.getHex()))
CMD:
node file.js
Result:
#2e5475
When I move that to my component...
import React, { Component } from 'react'
const Vibrant = require('node-vibrant');
class Hello extends Component {
helloPalette = palette => {
console.log(palette)
}
render() {
// I also tried here const Vibrant = require('node-vibrant');
return (
{
let v = new Vibrant('image.jpg')
v.getPalette((err, palette) => this.helloPalette(palette.Vibrant.getHex()))
}
)
}
}
export default Hello
I received the following error...
Error in ./src/Hello.js
Syntax error: C:/test/src/Hello.js: let is a reserved word (23:7)
21 | return (
22 | {
> 23 | let v = new Vibrant('image.jpg')
| ^
24 | v.getPalette((err, palette) => this.helloPalette(palette.Vibrant.getHex()))
25 |
26 | }
And...
If I change and move the var declaration to var v; below the function...
Failed to compile.
Error in ./src/Hello.js
Syntax error: C:/test/src/Hello.js: Unexpected token (10:4)
Or...
If I change and move the var before the return() as well nexpected token, expected ,
Can anyone provide light...? Does anyone use this or something similar with React...?
Will appreciate anyhelp.
Good weekend
You need to declare your object first and correct some syntax errors, THEN return it.
...
let v = new Vibrant('image.jpg')
return v.getPalette((err, palette) => this.helloPalette(palette.Vibrant.getHex()))
For people interested, you can use the react-palette package which does the job for you:
yarn add react-palette
And your code would look like this:
import Palette from 'react-palette'
<Palette image={IMAGE_URL}>
{palette => (
<div style={{ color: palette.vibrant }}>
Hello world
</div>
)}
</Palette>
The package uses node-vibrant under the hood thanks to an util function, so you can have a look at that if you are interested!

Can't render a local static image using React + Hapi

happiness#1.0.0 start C:\Users\Schrute\Documents\GitHub\happiness
node server.js
Server running at :http://localhost:5000
Debug: internal, implementation, error
SyntaxError: C:/Users/Schrute/Documents/GitHub/happiness/node_src/views/wiam.jpg: Unexpected character '?' (1:0)
1 | ???? ►JFIF ☺☻ ☺ ☺ ?? ?Photoshop 3.0 8BIM♦♦ ?∟☻g ¶uH7kKKuGKb3aEebAxn9b∟☻( bFBMD01000abe030000bc2d000015570000
5e590000395d0000ea75000056c2000021cd000030d400009bdb0000f8680100??☻∟ICC_PROFILE ☺☺ ☻♀lcms☻► mntrRGB XYZ ? ☺ ↓ ♥ ) 9acs
pAPPL ?? ☺ ?-lcms
| ^
2 | desc ? ^cprt ☺\ ♂wtpt ☺h ¶bkpt ☺| ¶rXYZ ☺? ¶gXYZ ☺? ¶bXYZ ☺? ¶rTRC ☺? #gTRC ☺? #bTRC
☺? #desc ♥c2 text FB XYZ
?? ☺ ?-XYZ ♥▬ ♥3 ☻?XYZ o? 8? ♥?XYZ b? ?? ↑?XYZ $? ☼? ??curv → ?☺?♥c♣k♂?►?
§Q4!?)?2↑;?F♣Qw]?kpz♣???|?i?}???0???? C ♠♦♣♠♣♦♠♠♣♠♠
3 | ►
4 |
at Parser.pp$5.raise (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babylon\lib\index.js:4454:13)
at Parser.getTokenFromCode (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babylon\lib\index.js:1147:10)
at Parser.readToken (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babylon\lib\index.js:776:19)
at Parser. (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babylon\lib\index.js:7214:20)
at Parser.readToken (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babylon\lib\index.js:6011:22)
at Parser.nextToken (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babylon\lib\index.js:766:19)
at Parser.parse (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babylon\lib\index.js:1672:10)
at parse (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babylon\lib\index.js:7246:37)
at File.parse (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babel-core\lib\transformation\file\index.js:
517:15)
at File.parseCode (C:\Users\Schrute\Documents\GitHub\happiness\node_modules\babel-core\lib\transformation\file\index
.js:602:20)
Here's the faulty snippet of code.
'use strict';
import React, { Component } from 'react';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {GridList, GridTile} from 'material-ui/GridList';
import wiam from './wiam.jpg';
injectTapEventPlugin();
class App extends Component {
render(){
return (
<div className="App">
<MuiThemeProvider>
<div>
<GridList cellHeight={100}>
{this.props.data.map((cat) => (
<GridTile key={cat.photo} title={cat.title}>
{console.log(cat.photo)}
<img src={cat.photo} alt={cat.photo}/>
</GridTile>))}
<GridTile key="wiam.jpg" title={process.env.PUBLIC_URL}>
<img src={wiam} />
</GridTile>
</GridList>
</div>
</MuiThemeProvider>
</div>
);
}
}
module.exports = App;
Note that I use React views throught routes with the Vision engine ( https://www.npmjs.com/package/hapi-react )
I am guessing the problem is happening due to this line: import wiam from './wiam.jpg';.
Node does not know how to import image files. In fact, it can only import JS modules. Not to be confused with bundled client side code which can be configured to deal with such import statements - i.e with webpack's file-loader.
In any case, in the following statement - <img src={wiam} /> - src attribute expects a string - either a URL that points to an image file or a base64 encoded image.

Categories