Trouble requiring a module in ReactJS - javascript

I am a beginner to the entire ReactJS ecosystem, and I am trying to build an app in React. I am using the create-react-app tool to create my app. Here is the relevant code to this problem:
App.js:
const findWord = require('../word'); //This is where I require the file
import React from 'react';
import ReactDOM from 'react-dom';
class Form extends React.Component {
constructor(){
super();
this.props = {
}
}
getWord(e){
e.preventDefault();
let word = ReactDOM.findDOMNode(this.refs.wordInput).value;
alert(word);
findWord();
}
render() {
return (
<div className="search">
<form className="pure-form">
<input ref="wordInput" type="text" placeholder="Search . . ."></input>
<button onClick={this.getWord.bind(this)} className="pure-button pure-button-primary" type="button">Go</button>
</form>
</div>
);
}
}
export default Form;
word.js:
var scraperjs = require('scraperjs'); //This is where I require the dependency
/* If I take the function out of the module.exports, then run the file with `node src/word.js`, it will work fine, but when I use it in the context of the application, then things go awry. */
module.exports = function(){
scraperjs.StaticScraper.create('https://news.ycombinator.com/')
.scrape(function($) {
return $(".title a").map(function() {
return $(this).text();
}).get();
})
.then(function(news) {
console.log(news);
})
};
My trouble is that when I try to require the module(scraperjs) from a component class and use it, it generates an error in some random dependency.
Error in ./~/win-spawn/index.js
Module not found: 'child_process' in /Users/marknifakos/Documents/new-react-app/word-map-shs/node_modules/win-spawn
# ./~/win-spawn/index.js 1:13-37
When I use this module in with the plain node cli command, it works just fine, so the problem probably doesn't lie with the dependency itself. And I am 100% sure that the paths are correct, so don't bring that up either.

This is happening because the child-process module is an inbuilt module in Node, and not accessible by the browser. This also why you are able to access it using the cli, but not in the browser because webpack does not bundle it. Your best bet is to include the following in your webpack config:
node:
{
"child_process": "empty"
}
And hope that your dependency does not need to use any methods from this module.

Related

Critical dependency warning when using react-pdf

I'm trying to display a pdf on a react application and i get the following warning:
/node_modules/react-pdf/node_modules/pdfjs-dist/build/pdf.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
Vscode tells me this under the import function.
Could not find a declaration file for module 'react-pdf'
Already tried running npm install, npm install react-pdf and reinstalling the package
import React, { Component } from 'react';
import { Document } from 'react-pdf';
import sample from 'file location'
export default class viewer extends Component {
render() {
return (
<div>
<Document
file={sample}
onLoadSuccess={this.onDocumentLoadSuccess}
>
</Document>
</div>
);
}
}
Displays:
"Failed to load PDF file" in the browser
This code will display your pdf file, but issue will display in IDE console.
import { Document, Page, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
In my case I'm using webpack 4 and it's not supportted yet.
If you build project it will work fine.
My full workaround.
Create a file at the root called config-overrides.js and it should contain the following:
module.exports = function override(config) {
config.module.rules[0].parser.requireEnsure = true
return config
};
After that npm i react-app-rewired to you app and change your build function in package.json to read react-app-rewired build/react-app-rewired start.
That should do it for now.

react-collapsible Failed to Compile

Im working on spring+reactJS project, currently working on front-end (begginer in this field).
Generally i try to create simple accordion from "REACT-COLLAPSIBLE".
Code is very Simple: JS File:
import React, { Component } from 'react';
import { Link } from "react-router-dom";
import '../index.css';
import Collapsible from "react-collapsible/src/Collapsible";
class Author extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Collapsible trigger="Start here">
<p>This is the collapsible content. It can be any element or React component you like.</p>
<p>It can even be another Collapsible component. Check out the next section!</p>
</Collapsible>
);
}
}
export default Author;
I have installed react-collapsible and i have proper dependency in package.json
When i try to compile this code i have compilation error:
Failed to compile.
./node_modules/react-collapsible/src/Collapsible.js
Module parse failed: Unexpected token (116:8)
You may need an appropriate loader to handle this file type.
| if (this.props.triggerSibling && typeof
this.props.triggerSibling === 'string') {
| return (
| <span className={`${this.props.classParentString}__trigger-
sibling`}>{this.props.triggerSibling}</span>
| )
| } else if(this.props.triggerSibling) {
Certainly this is only a part of project, except this part everything works. I have no idea what should i do, if error is connected with other part of code, which could be useful, let me know.
Sth is wrong with react-collapsible module? What should i do? When i installed it i didn't receive any WARN, that other dependency should be added
Change your import to import Collapsible from "react-collapsible";
You are importing from the src rather than the dist which has been processed.
If you checkout the package.json for this module you will see that the default exported file is dist/Collapsible.js.

How do you import a javascript package from a cdn/script tag in React?

I'd like to import this javascript package in React
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
However, there is no NPM package, so I can't import it as such:
import dwolla from 'dwolla'
or
import dwolla from 'https://cdn.dwolla.com/1/dwolla.js'
so whenver I try
dwolla.configure(...)
I get an error saying that dwolla is undefined. How do I solve this?
Thanks
Go to the index.html file and import the script
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
Then, in the file where dwolla is being imported, set it to a variable
const dwolla = window.dwolla;
This question is getting older, but I found a nice way to approach this using the react-helmet library which I feel is more idiomatic to the way React works. I used it today to solve a problem similar to your Dwolla question:
import React from "react";
import Helmet from "react-helmet";
export class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myExternalLib: null
};
this.handleScriptInject = this.handleScriptInject.bind(this);
}
handleScriptInject({ scriptTags }) {
if (scriptTags) {
const scriptTag = scriptTags[0];
scriptTag.onload = () => {
// I don't really like referencing window.
console.log(`myExternalLib loaded!`, window.myExternalLib);
this.setState({
myExternalLib: window.myExternalLib
});
};
}
}
render() {
return (<div>
{/* Load the myExternalLib.js library. */}
<Helmet
script={[{ src: "https://someexternaldomain.com/myExternalLib.js" }]}
// Helmet doesn't support `onload` in script objects so we have to hack in our own
onChangeClientState={(newState, addedTags) => this.handleScriptInject(addedTags)}
/>
<div>
{this.state.myExternalLib !== null
? "We can display any UI/whatever depending on myExternalLib without worrying about null references and race conditions."
: "myExternalLib is loading..."}
</div>
</div>);
}
}
The use of this.state means that React will automatically be watching the value of myExternalLib and update the DOM appropriately.
Credit: https://github.com/nfl/react-helmet/issues/146#issuecomment-271552211
for typescript developers
const newWindowObject = window as any; // cast it with any type
let pushNotification = newWindowObject.OneSignal; // now OneSignal object will be accessible in typescript without error
You can't require or import modules from a URL.
ES6: import module from URL
What you can do is make an HTTP request to get the script content & execute it, as in the answer for how to require from URL in Node.js
But this would be a bad solution since your code compilation would depend on an external HTTP call.
A good solution would be to download the file into your codebase and import it from there.
You could commit the file to git if the file doesn't change much & are allowed to do it. Otherwise, a build step could download the file.
var _loaded = {};
function addScript(url) {
if (!loaded[url]) {
var s = document.createElement('script');
s.src = url;
document.head.appendChild(s);
_loaded[url] = true;
}
}
how to load javascript file from cdn server in a component
Add the script tag in your index.html and if you are using Webpack, you can use this webpack plugin https://webpack.js.org/plugins/provide-plugin/

Node module not working in react and electron implementation

I am building a simple electron app using react, i needed to use the os.homedir method to get the home directory of the user.
Here is my react component,
import React, { Component } from 'react'
import Os from 'os'
export default class Item extends Component {
constructor( props ) {
super( props )
}
render () {
return (
<div className='item-component'>
{ Os.homedir() }
</div>
)
}
}
But seems that electron is not utilizing the os module of node js. Thus an
Uncaught TypeError: _os2.default.homedir is not a function
error occures.
Instead of importing the os module i also used the require method with no luck.
let Os = require( 'os' )
How to use node modules in electron and react setup?
Added Project to GitHub https://github.com/rakibtg/ElectronThisIsReact
You can clone it to test ....
I know this is like 4 months late... but if it helps now try using let Os = window.require( 'os' ).
In my app that i'm developing using react and electron if i did not say window.require I would get the same error.

Import components for server-side rendering in ES6

I've got a nice little ES6 React component file (simplified for this explanation). It uses a library that is browser-specific, store This all works beautifully on the browser:
/app/components/HelloWorld.js:
import React, { Component } from 'react';
import store from 'store';
export default class HelloWorld extends Component {
componentDidMount() {
store.set('my-local-data', 'foo-bar-baz');
}
render() {
return (
<div className="hello-world">Hello World</div>
);
}
}
Now I'm trying to get it to render on the server as follows, using babel-register:
/server/routes/hello-world.js:
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import HelloWorld from '../../app/components/HelloWorld'
export default function(req, res) {
res.render('root', {
reactHTML: ReactDOMServer.renderToString(<HelloWorld />),
});
}
I get an error from the node server saying "window is not defined" due to importing 'store'. Ideally I could conditionally import by detecting the environment (node vs browser), but conditional imports aren't supported in ES6.
What's best way to get around this? I don't actually need to execute the browser code (in this case componentDidMount won't be called by ReactDOMServer.renderToString) just get it running from node.
One way would be using babel-rewire-plugin. You can add it to babel-register via the plugins option
require('babel/register')({
plugins: ['babel-rewire-plugin']
});
Then rewire your store dependency to a mocked store:
HelloWorld.__Rewire__('store', {
set: () => {} // no-op
});
You can now render HelloWorld from the server peacefully.
If you want to suppress the load of some npm module, you can just mock it.
Put this on your node.js application setup, before the HelloWorld.js import:
require.cache[require.resolve('store')] = {
exports: {
set() {} // no-op
}
};
This value will be used instead of the real module, which doesn't need on your purposes. Node.js module API is stable, so this behavior will not be broken and you can rely on it.

Categories

Resources