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
Related
I working with framer-motion in my NextJS project. I'm trying to import {motion} using Next's dynamic import. But unfortunately, it doesn't seem to work.
import { motion } from "framer-motion"
I'm trying to convert the above import as a dynamic import as given below:
const motion = dynamic(() =>
import("framer-motion").then((module) => module.motion)
)
But it throws an error :
"Argument of type '() => Promise<ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; } | ((<Props>(Component: string | ComponentType<Props>, customMotionComponentConfig?: CustomMotionComponentConfig | undefined) => CustomDomComponent<...>) & HTMLMotionComponents & SVGMotionComponents)>' is not assignable to parameter of type 'DynamicOptions<{}> | Loader<{}>'."
Whenever I import other things like icons, custom components it works as expected, for example the dynamic import given below works fine :
const DoubleArrowRightIcon = dynamic(() => import("#radix-ui/DoubleArrowRightIcon"), {
loading: () => <p>..</p>,
})
I have looked at other answers and found this link but still, not able to make it work.
Any help please?
I have used pdf-viewer-reactjs into my Next.js project. But getting following error.
error - ./node_modules/pdfjs-dist/build/pdf.js 2094:26
Module parse failed: Unexpected token (2094:26)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| async destroy() {
| this.destroyed = true;
> await this._transport?.destroy();
| this._transport = null;
|
So far I've tried following both ways but nothing worked for me!
How to use this npm into my project without any errors?
The code (Way 1):
import React from 'react';
import StudentPortalLayout from "../../../components/Layout/StudentLayout";
import dynamic from "next/dynamic";
const PDFViewer = dynamic(() => import("pdf-viewer-reactjs"), {
ssr: false
});
function PDFView() {
return (
<StudentPortalLayout hideSidebar={true}>
<PDFViewer
document={{
url: 'https://arxiv.org/pdf/quant-ph/0410100.pdf',
}}
/>
</StudentPortalLayout>
)
}
export default PDFView;
The code (Way 2):
import React from 'react';
import StudentPortalLayout from "../../../components/Layout/StudentLayout";
import PDFViewer from 'pdf-viewer-reactjs'
function PDFView() {
return (
<StudentPortalLayout hideSidebar={true}>
<PDFViewer
document={{
url: 'https://arxiv.org/pdf/quant-ph/0410100.pdf',
}}
/>
</StudentPortalLayout>
)
}
export default PDFView;
I was able to run the following code successfully, however it requires additional steps
Install the babel runtime - yarn add #babel/runtime - courtesy this post.
Material UI icon gives an error, so similarly add the material UI dependencies
Assuming this is what you want:
Stackblitz - https://stackblitz.com/edit/nextjs-utkd32?file=pages%2Findex.js
import Head from 'next/head';
import styles from '../styles/Home.module.css';
import PDFViewer from 'pdf-viewer-reactjs';
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
</Head>
<main className={styles.main}>
<PDFViewer
document={{
url: 'https://arxiv.org/pdf/quant-ph/0410100.pdf',
}}
/>
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
</a>
</footer>
</div>
);
}
Dynamic Imports
If you want to do a dynamic import as you were trying to do above, the export of the individual module maybe need to linked to - potentially pdf-viewer-reactjs/pdf-viewer-reactjs - This needs more to be looked into.
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.
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!
I've created a new React project in Webstorm. I've installed draft-js and draft-js-plugins-editor, along with the plugins draft-js-hashtag-plugin and draft-js-mathjax-plugin (Using node).
I've following their 'getting started' on their Github, however the example doesn't work for me. As soon as I write
import Editor from 'draft-js-plugins-editor';
I get an TypeError: Cannot read property 'object' of undefined error.
./node_modules/draft-js-plugins-editor/lib/Editor/index.js
node_modules/draft-js-plugins-editor/lib/Editor/index.js:177
174 | }(_react.Component);
175 |
176 | PluginEditor.propTypes = {
> 177 | editorState: _react2.default.PropTypes.object.isRequired,
178 | onChange: _react2.default.PropTypes.func.isRequired,
179 | plugins: _react2.default.PropTypes.array,
180 | defaultKeyBindings: _react2.default.PropTypes.bool,
My minimal example code:
import React, { Component } from 'react';
import Editor from 'draft-js-plugins-editor'; // Error upon doing this
import createHashtagPlugin from 'draft-js-hashtag-plugin';
import { EditorState } from 'draft-js';
const hashtagPlugin = createHashtagPlugin();
const plugins = [
hashtagPlugin,
];
export default class MyEditor extends Component {
state = {
editorState: EditorState.createEmpty(),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
render() {
return (
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
/>
);
}
}
This error appears because of you use the latest (16th) version of React.js. In this blog post (announce of React.js version 16) you can read:
The deprecations introduced in 15.x have been removed from the core
package. React.createClass is now available as create-react-class,
React.PropTypes as prop-types...
All old packages which still accessed React.PropTypes will be broke if you use these with React 16.
If you want to use draft-js-plugins-editor you must downgrade your react version to version 15. For example, for npm use this command
npm install react#15.4.2 --save
or this for yarn:
yarn add react#15.4.2