Node module not working in react and electron implementation - javascript

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.

Related

Parcel.js Error When Executing On Google Scripts

I'm developing a React App and pushing the files using Clasp to my google scripts webapp. Parcel.js is being used for compiling. Here's a basic React App that works:
index.js
import { createRoot } from 'react-dom/client';
import App from './App';
const container = document.getElementById('app');
const root = createRoot(container); // createRoot(container!) if you use TypeScript
root.render(<App />);
App.js
//app.js
const App = () => {
return <div>Hello App!</div>
}
export default App
But as soon as I add one #mui/material/ import into App.js I'm getting an error.
import Button from "#mui/material/Button"
const App = () => {
return <div>Hello App!</div>
}
export default App
Notice that I'm not even using the Button. Locally there's no error but when running on google scripts webapp, I get a console error:
Uncaught SyntaxError: missing ) after argument list
Obviously, Parcel is not compiling something correctly but I can't figure it out. Thanks in advance for the help.

Office Add-ins excel extension is not working on IE11 with 'import axios' statement

I'm currently developing a Excel extension for my company with Office Add-ins and Reactjs.
Lately I've been using Axios in order to make http requests to get data from a remote back-end service. The issue is that the statement "import axios from 'axios'" is not handled in IE11 and the application runs into an exception when this statement is present in a script file. The exception is :
Office.js has not fully loaded. Your app must call "Office.onReady()" as part of it's loading sequence (or set the "Office.initialize" function). In itself that doesn't say a lot except that "the code does not compile".
After a few researches on my own I discovered that IE11 needs polyfill in order to make it work since it doesn't natively support the most recent js scripts (ES6, promises by example).
I've tried many kinds of combinations with babel/polyfill, react-app-polyfill, es-promise with no result so far. Happily, in a another application I've been working on recently (VueJs with axios), I met the same problem and just adding 'import babel/polyfill' did the trick.
I would like to know if anyone has succeeded in doing what I am trying to do for a few days and if not, any help will be appreciated. Some of my coworkers are using Windows 7 or Windows Server 2019 and I really need this excel extension to function with IE11.
Thank you for your help.
Edit on 06/29 :
Here is what I have in my index.js :
import "office-ui-fabric-react/dist/css/fabric.min.css";
import App from "./components/App";
import { AppContainer } from "react-hot-loader";
import { initializeIcons } from "office-ui-fabric-react/lib/Icons";
import * as React from "react";
import * as ReactDOM from "react-dom";
/* global AppCpntainer, Component, document, Office, module, React, require */
initializeIcons();
let isOfficeInitialized = false;
const title = "Contoso Task Pane Add-in";
const render = Component => {
ReactDOM.render(
<AppContainer>
<Component title={title} isOfficeInitialized={isOfficeInitialized} />
</AppContainer>,
document.getElementById("container")
);
};
Office.initialize = () => {
isOfficeInitialized = true;
render(App);
};
render(App);
if (module.hot) {
module.hot.accept("./components/App", () => {
const NextApp = require("./components/App").default;
render(NextApp);
});
}
commands.js : You can see that I have a commented import statement in this file regarding axios. My intent is to make it work in the dataservice instead but I put that statement here just for testing purpose. The dataservice class itself has only one dependency : axios.
import "babel-polyfill";
// import axios from 'axios';
import DataService from '../server/dataservice';

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.

Trouble requiring a module in ReactJS

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.

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