I have created one React App using npx create-react-app my-app cmd (React 17 version). Now
Well, I just tried to replace a classic
import Component from './Component'
to
const Component = React.lazy(() => import('./Component'));
and then
<React.Suspense fallback={<div>Loading.. </div>}>
<Component />
</React.Suspense>
but it throws error like
SyntaxError: Unexpected token at import(6:22)
> 6 | const Component = React.lazy(() => import('./Component'));
Can anyone help me to resolve this?
This is the code syntax
And this is the suspense component
And this is the compilation output
My package.json looks like
I'm not sure, if this fixes your issue, but maybe you can give it a try. Are you using Babel?
It says:
When using Babel, you’ll need to make sure that Babel can parse the
dynamic import syntax but is not transforming it. For that you will
need #babel/plugin-syntax-dynamic-import.
https://reactjs.org/docs/code-splitting.html#import
I've created a .babelrc file on the project root and added the content:
{
"plugins": [
"#babel/plugin-syntax-dynamic-import"
]
}
I also imported lazy in my component:
import React, { Component, lazy, useEffect, useState } from 'react';
In my project React.lazy is working fine this way.
Related
I'm working on a single-spa React version 5.9.4, which currently it is configured with react 17. But when I try to update to React 18, it doesn't recognize the createRoot method from DOMClient, which is set up like this:
react-mf-hello-world.tsx file
import React from 'react';
import * as ReactDOMClient from 'react-dom/client';
import singleSpaReact from 'single-spa-react';
import Root from './root.component';
const lifecycles = singleSpaReact({
React,
ReactDOMClient,
rootComponent: Root,
// eslint-disable-next-line #typescript-eslint/no-unused-vars
errorBoundary(err, info, props) {
// Customize the root error boundary for your microfrontend here.
return null;
},
});
export const { bootstrap, mount, unmount } = lifecycles;
And this is the error I'm getting:
console
*Even though I have configured React 18, it's using the render method, so it behaves like React 17.
** Uncaught TypeError: application '#react-mf/hello-world' died in status SKIP_BECAUSE_BROKEN: m.createRoot is not a function**
versions dependencies of my proyect:
react 18.2.0
react-dom 18.2.0
single-spa 5.9.4
single-spa-react 5.0.0
webpack 5.75.0
Any help is greatly appreciated!
I was able to solve it! The problem was that I needed to update the cdn react version of the root project of my single spa.
I hope someone can tell me where I am going wrong in trying to get usable libraries
I have created a NPM project using create-react-app --format typescript, I then created the following structure:
|->tsconfig.json
|->package.json
|->config
|->tsconfig.base.json
|->tsconfig.cjs.json
|->tsconfig.esm.json
|->src
|->index.tsx
|->components
|->index.ts
|->ExampleComponent
|->ExampleComponent.component.tsx
|->ExampleComponent.stories.tsx
|->ExampleComponent.types.ts
|->index.ts
In this example the Example Component looks something like the following:
|->tscon
import React, { FC } from 'react';
// Contact specific icons
import Container from 'react-bootstrap/Container';
// Footer Properties
import { ExampleProperties } from './ExampleComponent.types';
export const ExampleComponent: FC<ExampleProperties> = ({ text }) => {
return (<Container fluid>{text}</Container>);
};
for the tsconfig files in 'config' I've lifted the Synk recommendation directly, while tsconfig.json is fairly simple like so:
{
"extends": "./configs/tsconfig.esm.json",
}
If I start the application via 'npm start' I get a website and the component correctly appears, but the issue is trying to import into another project.
I using npm link and npm link #Example/ExampleProject to bring the project in to another website and the index.tsx of that project looks like so:
import React from 'react';
import { createRoot } from 'react-dom/client';
import { ExampleComponent } from '#Example/ExampleProject';
const container = document.getElementById('root');
if (!container) throw new Error('Failed to find the root element') const root = createRoot(container);
root.render(
<React.StrictMode>
<main role={"main"} >
<ExampleComponent/>
</main>
</React.StrictMode> );
But when it starts I am getting this error:
Module not found: Error: Can't resolve './ExampleComponent/index' in '/home/user/IdeaProjects/ExampleProject/dist/esm' Did you mean 'index.mjs'? BREAKING CHANGE: The request './Common/index' failed to resolve only because it was resolved as fully specified (probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"'). The extension in the request is mandatory for it to be fully specified. Add the extension to the request.
The only thing I can think is tsc generates src/components/index.ts as a /src/component/index.js (which I rename). But ExampleComponent has .js and .mjs files within its directory
I am writing a component that makes use of another component, so I've written
import { Text } from "../Text/Text"
in the file /src/stories/TextArea/TextArea.tsx.
However, this gives the error
Module not found: Can't resolve '../Text/Text' in '/Users/username/project/src/stories/TextArea'
Changing the import statement to
import { Text } from "../Text/Text.tsx"
makes it work just fine. Instead, the linter complains:
An import path cannot end with a '.tsx' extension. Consider importing '../Text/Text.js' instead.ts(2691)
As I understand it, .tsx endings are forbidden in TypeScript so reconfiguring the linter doesn't seem to be the best option.
Obviously, importing Text.js instead doesn't work as it doesn't exist. Storybook is supposed to work out of the box with TypeScript, so I'm unsure of what I have to do.
In the .mdx files I am using as stories (like Text.stories.mdx), imports including .tsx are accepted without linter complaints. Removing the extension produces a similar Module not found error.
The project was created with create-react-app and is running Storybook 6.5.15.
your import import { Text } from "../Text/Text" should work fine.
Make sure you are using the latest version of Storybook - 6.5.15.
...
I tried to reproduce your issue and failed to do so. I did not get the same error and the import worked just fine. Let me describe what steps I took:
I installed Storybook in my project using npx storybook init --type react. This installed Storybook 6.5.15 for React.
I created a simple component in ./project/src/Button.tsx
import React from 'react'
export const Button = () => {
return <div>MY BUTTON</div>
}
I created a simple story in ./project/stories/Button.stories.jsx like this:
import React from 'react';
import { Button } from '../src/Button';
// More on default export: https://storybook.js.org/docs/react/writing-stories/introduction#default-export
export default {
title: 'Example/Button',
component: Button,
// More on argTypes: https://storybook.js.org/docs/react/api/argtypes
argTypes: {
backgroundColor: { control: 'color' },
},
};
// More on component templates: https://storybook.js.org/docs/react/writing-stories/introduction#using-args
const Template = (args) => <Button {...args} />;
export const Primary = Template.bind({});
// More on args: https://storybook.js.org/docs/react/writing-stories/args
Primary.args = {
primary: true,
label: 'Button',
};
And there are no issues. The import works as it should. If this does not help you, tell us more about your project setup (e.g. are you using Create-react-app), etc. So this issue is easier to reproduce.
Yesterday I developed a react custom hook for making our react application's title as dynamic and published in npm. It is my first attempt in npm contribution. So I faced so many errors. And one error not fixed after my well effort. The problem is as below:
The hook using useRef, and useEffect.
The version of react used by the hook is 18.2.0
dependencies in this format:
"dependencies": {
"react": "^18.2.0"
}
I used the hook like this:
import React from "react";
import useTitle from "./hook/react-title-hook";
// import useTitle from "./title";
// import useTitle from "react-dynamic-title";
import { useNavigate } from "react-router-dom";
function App() {
const navigate = useNavigate();
useTitle("Home");
return (
<div className="App">
<header className="App-header">
app
</header>
<h1
onClick={() => {
navigate("/somting");
}}
>
somithing
</h1>
</div>
);
}
export default App;
There are 4 scenarios:
The hook has not a special package.json nor node_modules and it is using what the whole project uses in common. Then, there is no problem. it works smoothly. (It is like second useTitle of the above code)
The hook installed from npm and the version of react in main project is same as the version of hook 18.2.0 , so it would not install the dependencies specially. Then, there is no problem. It works smoothly. (It is like third useTitle of the above code)
The hook has special package.json and node_modules (because, we want to initialise and mention the dependencies when we publish our package). (It is like first useTitle of the above code) Then, the app not render and throw these two errors:
Invalid hook call. Hooks can only be called inside of the body of a function component. (actually the hook is inside of the component)
Uncaught TypeError: Cannot read properties of null (reading 'useRef'). (the first line of hook is useRef, so the error is like this. When I changed and make the useEffect the error is like cannot read properties of null (reading 'useEffect'))
The hook installed into a project that the version of react used by that project is not matching of the version of the hook. Then, the app throw the error as above.
So, this is the problem. The link of the hook is this: react-dynamic-title
How to fix it, Thank you in advance.
I'm trying to use lazy loading for my create-react-app with react#16.5.2 and I did this :
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
const Header = React.lazy(() => import('./_header'));
class SomeFile extends Component {
render() {
return (
<BrowserRouter>
<React.Fragment>
<Header />
</React.Fragment>
</BrowserRouter>
);
}
}
export default SomeFile;
Do you know why this error occurs ? is it because of my react version ? based on this everything seems fine!
Edit
What does this mean? based on reactjs.org :
Note:
React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we recommend Loadable Components. It has a nice guide for bundle splitting with server-side rendering.
React.lazy is only available from v16.6.0 https://reactjs.org/blog/2018/10/23/react-v-16-6.html
In your comand line interface, try updating React using the following command:
npm i react#latest
Restart Development Server, if you still face issue try the above steps:
Search for REACT_EDITOR on the Readme.md file, and insert =atom in front of it, like as follow:
REACT_EDITOR=atom
Then, save, restart the development server. It should work now