I am developing application using create-react-app, and using third party module which is not compile, I am including JSX file from this to my project.
getting following error when start or build
******.jsx
Module parse failed: Unexpected token (12:25)
You may need an appropriate loader to handle this file type.
My react application is not eject and don't want to eject.
I don't want to eject from react-script
Sample code
Link.jsx in Library
import React from 'react';
import { string } from 'prop-types';
import './Link.scss';
const STATUS = {
HOVERED: 'hovered',
NORMAL: 'normal',
};
class Link extends React.Component {
constructor(props) {
super(props);
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
this.state = {
className: STATUS.NORMAL,
};
}
onMouseEnter() {
this.setState({ className: STATUS.HOVERED });
}
onMouseLeave() {
this.setState({ className: STATUS.NORMAL });
}
render() {
const { className } = this.state;
const { page, children } = this.props;
return (
<a
className={className}
href={page}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
>
{children}
</a>
);
}
}
Link.propTypes = {
page: string,
children: string,
};
Link.defaultProps = {
page: '#',
children: '',
};
export default Link;
Above code is publish to internal npm repo and used in application
App.jsx in application
import { Link} from '#myScope/myreactlib/Link'; // loaded from node_modules
App.jsx give error
When using create-react-app without ejecting, you will have some restrictions on how you can import modules.
If it is a custom module that you have built, then it needs to be in your src folder, and you import it using a path relative to your current file's path. For example: import MyComponent from './components/MyComponent
If it comes from a third-party dependency package (for example, reactstrap or #blueprintjs/core) which you have already added with npm or yarn, then you import it simply by specifying the package name. For example: import { Button } from 'reactstrap'
In your case, it sounds like you have a sub-folder in your node_modules folder which is for a package that you did not add with npm or yarn. While I doubt that it's recommended to use third-party packages this way, I'll assume that you have a good reason for doing so.
Without being able to see your entire setup, I would propose you try the following workaround:
In your src folder, create a symlink to the folder with your third-party package. For example (while in your project's src folder):
ln -s ../node_modules/#myScope/myreactlib myreactlib
Then, in your App.jsx file, do:
import { Link } from './myreactlib/Link'
Additional Information:
StackOverflow: The create-react-app imports restriction outside of src directory
StackOverflow: Import module from node_modules (create-react-app)
create-react-app documentation on importing a component
Related
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.
I have got a problem, I tried everything so far and with no success. I have installed react, react-native comes with it, but when I try importing components I get ``
This is Register.js code, I have these imports:
import React, { Component } from "react";
import { View, Text } from "react-native";
And class:
class Register extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<View>
<Text>Hello</Text>
</View>
);
}
}
export default Register;
I'm trying to use <View> and <Text>, but I get this error: Module not found: Can't resolve 'react-native' in 'D:\Darbai\2 kursas 2 semestras\Lankstusis prog. kurimas\Git workspace\team01\research\todosi-react\src\components\user_management' My guess is it's trying to find react-native in components\user_management folder, can this be a problem? Also Here is my files hierarchy.
Just found out I needed to install all dependencies, it solved my problem. I installed these dependencies with command npm install <dependency_name>:
react-scripts,
react-dom,
react-native-web,
react-art,
react-router-native,
react-router-dom
SnapSVG extension for Adobe Animate.cc 2017 is able to create interactivity and animations for the web. I'm currently trying to use an exported SnapSVG Adobe Animate.cc project in my REACT JS WebApplication.
What I've done so far:
Imported snapsvg-cjs from npm( modified snapsvg to use succesfull in React)
Imported axios to load custom json file generated from SnapSVG extension in Animate.cc
Excluded minified code with eslintignore from SnapSVGAnimator. lib, generated while publishing SVG animation from Animate.cc to work properly without the ESlinting warnings.
Create a componentDidMount function
current code:
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { SVGAnim } from './SnapSVGAnimator.js';
import snapsvg from 'snapsvg-cjs';
componentDidMount(){
axios.get(jsonfile)
.then(response => {
const json = response.request.responseText;
const comp = new SVGAnim(json);
console.log(comp)
});
}
Problem
Following error appears while I log const comp.
Uncaught (in promise) TypeError:
_SnapSVGAnimator.SVGAnim is not a constructor
During the publish render in Animate.cc there are two libs generated; snapsvg.js and SVGAnimator.js
You can import snapsvg-cjs from NPM but SVGAnimator.js isn't available. Importing SVGAnimator.js with the ES6 approach from a curtain directory in your ReactApp isn't possible, not even by excluding it from linting with /* eslint-disable */ 1000 warnings still appears.
Instead of that, add the code to your index.html file, located in the public folder this way
(I've used create-react-app to build this project):
<script type="text/javascript" src="%PUBLIC_URL%/libs/SnapSVGAnimator.min.js"></script>
This is the working code:
import React, { Component } from 'react';
//axios for asnyc usage*/
import axios from 'axios';
//Snapsvg-cjs works out of the box with webpack
import Snapsvg from 'snapsvg-cjs';
//snap.json is located in the public folder, dev-build folder(ugly approach).
let jsonfile = "snap.json";
class SVGAnimator extends Component {
constructor(props){
super(props);
this.state = {
data: ''
}
}
componentDidMount(){
axios.get(jsonfile)
.then(response => {
this.setState({ data: response.data })
});
}
getSVG(){
if(this.state.data){
const container = document.getElementById('container');
const SVG = new window.SVGAnim(this.state.data, 269, 163, 24)
container.appendChild(SVG.s.node);
}
}
render() {
return (
<div id="container">
{ this.getSVG()}
</div>
);
}
}
export default SVGAnimator;
I am trying to develop an NPM module that will provide react components. Right now, I'm just trying to set up the package and cannot get JSX in the components to be recognized in an example react project using the library.
My npm package project has one component:
import React from 'react';
class AfWin extends React.Component {
render() {
return <div></div>;
}
}
export default AfWin;
And this component is referenced in the index.js file pointed to as main in the package.json file:
import AfWin from './AfWin';
export default { AfWin };
To pack and import this package, I use a command prompt and type: npm pack. Then, I go to my example create-react-app and import the created .tgz file with npm install C:\path\to\file.tgz. This works, and I am able to get the AfWin component in my example app. However, the <div></div> or any JSX I try causes a problem at runtime:
Module parse failed: C:\path\to\project\node_modules\module-name\AfWin.js Unexpected token (6:15)
You may need an appropriate loader to handle this file type.
|
| render() {
| return <div></div>;
| }
| }
To make the problem more concrete, I published my broken module to npm: npmjs.com/package/react-affine