How to "require" a JS class that contains JSX? - javascript

I'm trying to call functions of my JS class which extends react.
I have one file RunTest.js which looks like this:
let Builder = require('./Builder');
let b = Builder();
b.say("Hello World!");
My Builder.js in the same directory looks something like this:
class Builder extends React.Component{
...
}
module.exports = { Builder }
And when I run with node RunTest.js I receive the following error:
bash-3.2$ node RunTest.js
/Users/jonahlibrach/Documents/project/prototypes/bron/v1/java/prototype/
server/static/protocol/Builder.js:322
<div class="navbar">
^
SyntaxError: Unexpected token <
at Module._compile (internal/modules/cjs/loader.js:743:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:810
:10)
at Module.load (internal/modules/cjs/loader.js:666:32)
at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
at Function.Module._load (internal/modules/cjs/loader.js:598:3)
at Module.require (internal/modules/cjs/loader.js:705:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/Users/jonahlibrach/Documents/project/prototy
pes/bron/v1/java/prototype/server/static/protocol/RunTest.js:1:15)
at Module._compile (internal/modules/cjs/loader.js:799:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:810
:10)
How do I use this class in node?

You cannot use modules that contain JSX in Node.js without first transpiling them to JavaScript (e.g. with Babel).

Related

Is there a way to get a variable or function from one file to another file in javascript?

I have a file for my Blockchain called gale.js, and I need the Blockchain variable to get into my miner.js file:
let galeCoin = new Blockchain(); // My Blockchain
Can I access this variable from my miner.js file so I can run the minePendingTransactions() function from the Blockchain class
var galeCoin = /* the coin imported from the gale.js file */
var minerAdress = "0xOTUYboIUYEO5C274OUIYGo8isYOCYW6o87TO"; // SHA256 Hash for the miner
while (true) {
minePendingTransactions(minerAdress); // mine (forever)
}
I would also like to access this variable in my user.js file:
var galeCoin = /* the coin imported from the gale.js file */
var userAdress = galeCoin.newAdress(); // A new adress for the user
// I will add the code here later...
And many other files!
But I can't seen to access the variable from the other files!
I tried this:
let galeCoin = new Blockchain();
export { galeCoin };
import { galeCoin } from './gale.js'
but that gives me this error when I run miner.js using node miner.js:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module 'gale.js'
Require stack:
- /Users/Movies/Desktop/devProjects/Blockchain/SecondTry/miner.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/Movies/Desktop/devProjects/Blockchain/SecondTry/miner.js:1:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/Users/Movies/Desktop/devProjects/Blockchain/SecondTry/miner.js' ]
}
I dont understand the error message
I need help as soon as posible!
NOTE: My files are in /Users/Movies/Desktop/devProjects/Blockchain/SecondTry/
Try using the following to import galeCoin from gale.js:
var {galeCoin} = require('./gale.js');
You'll also need to export the galeCoin object from gale.js. You can use the following (append somewhere at the end of gale.js):
module.exports = {galeCoin};
Then you're going to want to run npm install gale.js to ensure that module is added to the node_modules directory. For this you're going to want to make sure the node_modules is in the same director as miner.js. If it is not, npm -g install gale.js.
I should note, I'm assuming you're using node.js, which from the error you threw, seems to be the case.
I hope this was helpful:)
Try :
export let galeCoin = new Blockchain();
//add export statement at the beginning of the line where you declare your variable
You can read about it here: https://javascript.info/import-export

DateFormat.js SyntaxError: Unexpected token export

Using this with some Kubernetes PODS and one of the pods out of the blue gives me this error. It seems to come from the call on line 6. Have not changed anything was just doing a deployment on gitlab and noticed this POD said CrashLoopBackOff.
/app/config/auth.js line 6
var dateFormat = require('dateformat');
My nodemodules folder has the latest dateFormat.js from package.json
So not sure what the problem is. Does someone know how to fix it?
var token=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g;var timezone=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g;var timezoneClip=/[^-+\dA-Z]/g;export default function dateFormat(date,mask,utc,gmt){if(arguments.length===1&&typeof date==="string"&&!/\d/.test(date)){mask=date;date=undefined}date=date||date===0?date:new Date;if(!(date instanceof Date)){date=new Date(date)}if(isNaN(date)){throw TypeError("Invalid date")}mask=String(masks[mask]||mask||masks["default"]);var maskSlice=mask.slice(0,4);if(maskSlice==="UTC:"||maskSlice==="GMT:"){mask=mask.slice(4);utc=true;if(maskSlice==="GMT:"){gmt=true}}var _=function _(){return utc?"getUTC":"get"};var _d=function d(){return date[_()+"Date"]()};var D=function D(){return date[_()+"Day"]()};var _m=function m(){return date[_()+"Month"]()};var y=function y(){return date[_()+"FullYear"]
SyntaxError: Unexpected token export
at Module._compile (internal/modules/cjs/loader.js:760:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
at Module.require (internal/modules/cjs/loader.js:723:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/app/config/auth.js:6:18)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
at Module.require (internal/modules/cjs/loader.js:723:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/app/config/passport.js:8:18)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)```
Was able to fix it by downloading an older version of dateformat. Nothing wrong with my code on the question its a simple problem with the library not the code come on.
Here I could make it work by using another version of this package,was working in the version 4.6.3, so I did:
npm i dateformat#4.6.3

Static variable in nodejs

I am using ES6 style code within NodeJS.
When trying to create a static variable I get an error.
Code:
'use strict';
module.exports = class Count {
static addToCounter() {
//this.count = this.count + 1 || 1;
this.count = this.count + 1;
console.log(`count: `+this.count);
}
static count = "";
}
Error:
static count = "";
^
SyntaxError: Unexpected token =
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:646:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
What is my mistake?
This proposal is still in stage-2. As of now, without the babel plugin transform-class-properties, it is not possible to use the assignment operator along with the static keyword.
If you are not transpiling, you will need to be using at least Node.js v12.4.0 for static class fields. https://node.green/#ESNEXT-candidate--stage-3--static-class-fields-public-static-class-fields shows supported features across Node.js versions.
Also, inside your addToCounter function, you would also need to use Count.count = Count.count + 1. If you want to be able to store properties on each instance, then you would need to remove the static keywords before both the method and the property declaration.

Module not found unless I use a complete path when creating plugins in Hapi

I'm trying to familiarise myself with HapiJS and have been playing around with it this week, I've run into a problem with plugins and paths. I get an error regarding the path I specify when I require a file. I can't use " ./ " without getting an error. The only way to overcome the error is to use the full complete path.
Here's my code that works:
'use strict';
const indexController = require('/Users/mylaptop/docker-node/controllers/IndexController.js');
module.exports.plugin = {
name: 'myPlugin',
version: '1.0.0',
register: async function (server, options) {
// Create a route for example
server.route({
method:'GET',
path:'/test',
handler: function (request, h) {
return indexController.loadIndex(h);
}
});
}
};
However, if I try to require my IndexController file this way:
const indexController = require('./controllers/IndexController.js');
Then I get this error:
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module '/Users/mylaptop/docker-node/Users/mylaptop/docker-node/controllers/IndexController.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/mylaptop/docker-node/config/routes/index.js:5:25)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
It doesn't work inside of my plugin, yet outside of my plugin, requiring files this way works fine.
What could be the problem? How can I solve it?
Thanks in advance.
Problem solved with:
const indexController = require('../../controllers/IndexController.js');
My project root folder was 2 directories away, hence ../../ working for me.

Why quotes in attribute name raise an error?

When I execute a file with node.js containing only {"test":1}, a SyntaxError is raised :
(function (exports, require, module, __filename, __dirname) { {"test":1}
^
SyntaxError: Unexpected token :
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
But {test:1} (without quotes) or var t = {"test":1} works fine.
I execute the file containing the code running : node test.js.
Why ?
{} forms a block.
test: is a label, which is valid (but pointless since there is no loop).
"test": is a string, followed by a colon, which is nonsense.
var foo = {} puts the {} in a different context, so they form an object literal instead of a block. Inside an object literal, property names can be identifiers or strings.
Your test.js content looks like JSON, not JavaScript. It makes no sense to execute it because it doesn't do anything.

Categories