Can not import custom created class in JS - javascript

I am importing the following class which I created like so
import Select from './operations/select.js'
select.js
export default class Select{
constructor(db){
this.db = db
}
allGenres(){
return new Promise((res,rej)=>{
this.db.all(`SELECT * FROM genre`,(err,rows)=>{
if(err) res(err)
else res(rows)
})
})
}
}
I wish to do something like
return await new Select(db).allGenres()
But I am getting the following
(node:38769) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/home/lucky/workspace/web/vibe-backend/index.js:2
import Select from './operations/select.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (node:internal/modules/cjs/loader:1018:16)
at Module._compile (node:internal/modules/cjs/loader:1066:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
thank you for yout time.

Change to:
const Select = require('./operations/select.js');

Related

why am i not able to import the class to another js file

class hello{
var1;
var2;
constructor(var1, var2){
this.var1 = var1;
this.var2 = var2;
}
getVar(){
console.log(this.var1);
console.log(this.var2);
}
}
class h1 extends hello{
var3 ;
constructor(var1, var2,var3)
{
super(var1,var2);
this.var3 = var3;
}
getAll(){
console.log(this.var1);
console.log(this.var2);
console.log(this.var3);
}
}
export {h1};
export {hello};
This is a module that I want to import from another file
This is the code of another file
import {h1,hello} from './temp'
let a = new h1("likith","ramu","asha");
a.getAll();
let b = new hello("raju","rahil");
b.getVar();
And this is the error that I'm getting for this code Please solve this problem
**
(node:14232) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use node --trace-warnings ... to show where the warning was created)
c:\Full stack dev Code\react.js\temp1.js:1
import {h1,hello} from './temp'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159: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:77:12)
at node:internal/main/run_main_module:17:47
[Done] exited with code=1 in 0.125 seconds
**
Since you are trying to import a module it will be better if you try exporting your classes as a module as well, like this, module.exports = { h1, hello };
and then you can import it in your other file like this, const { h1, hello } = require("./temp");.
Hope this solves your problem

Why is animejs throwing this error on build in the svelte-kit skeleton project?

I've installed animejs with npm using
npm install animejs
<script>
import anime from 'animejs';
let heroTimeline = anime.timeline({autoplay: true});
let heroAnimation = {
targets: "#hero grow",
opacity: {
value: [0, 1],
duration: 800,
easing: 'easeOutExpo',
},
scale: {
value: [0, 1],
duration: 1000,
easing: 'easeOutElastic(1, .8)',
}
}
</script>
This code throws the following error:
ReferenceError: window is not defined
at makePromise (D:\Sync\Web\portfolio-website\node_modules\animejs\lib\anime.js:927:19)
at anime (D:\Sync\Web\portfolio-website\node_modules\animejs\lib\anime.js:933:17)
at Function.timeline (D:\Sync\Web\portfolio-website\node_modules\animejs\lib\anime.js:1264:12)
at index.svelte:4:39
at Object.$$render (D:\Sync\Web\portfolio-website\node_modules\svelte\internal\index.js:1684:22)
at Object.default (root.svelte:38:46)
at Object.default (/src/routes/__layout.svelte:12:50)
at eval (/src/lib/ThemeContext.svelte:46:41)
at Object.$$render (D:\Sync\Web\portfolio-website\node_modules\svelte\internal\index.js:1684:22)
at eval (/src/routes/__layout.svelte:11:100)
I also get the same error from importing from 'animejs/lib/anime.js' and 'animejs/lib/anime.min.js'.
If I try importing from 'animejs/lib/anime.es.js' I get the following error:
D:\Sync\Web\portfolio-website\node_modules\animejs\lib\anime.es.js:1310
export default anime;
^^^^^^
SyntaxError: Unexpected token 'export'
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
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 Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at nodeRequire (D:\Sync\Web\portfolio-website\node_modules\vite\dist\node\chunks\dep-85dbaaa7.js:66556:17)
at ssrImport (D:\Sync\Web\portfolio-website\node_modules\vite\dist\node\chunks\dep-85dbaaa7.js:66498:20)
Any ideas on how to fix it. Other than this the project is the default svelte skeleton project generated by svelte-kit.
Try to use onMount function
for exemple:
<script>
import { onMount } from 'svelte';
import anime from 'animejs';
onMount(() => {
let heroTimeline = anime.timeline({autoplay: true});
</script>
in onMount function you can use vanilla javascrpt

JavaScript problem with import, weird error

I have some code using library:
import { generateKeyPair } from 'jose/util/generate_key_pair'
async function funkcja () {
const {publicKey, privateKey} = await generateKeyPair('PS256')
console.log(publicKey)
console.log(privateKey)
}
funkcja()
and while trying to node it i get following error:
ubuntu#ubuntu-VirtualBox:~/Desktop/js$ node hello.js
/home/ubuntu/Desktop/js/hello.js:1
import { generateKeyPair } from 'jose/util/generate_key_pair'
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
I have no idea why this is happening, my friend is using exact same library and same code and on his computer it's working fine. (path to the library is correct) The only differennce is that he has node v12 and i have node v10.
Try this one
const { generateKeyPair } = require('jose/util/generate_key_pair');
Don't forget to use module.exports in generate_key_pair js file
How i read it in Update on ES6 Modules in Node.js the import of variables via curly brackets seems to be not supported in node.js.
it will simply not be possible to use the syntax:
import {foo, bar} from 'foobar';
But this would be possible:
import foobar from 'foobar';
console.log(foobar.foo(), foobar.bar());
So if generateKeyPair is a variable or function from 'jose/util/generate_key_pair' it should be:
import generate_key_pair from 'jose/util/generate_key_pair'
async function funkcja () {
const {publicKey, privateKey} = await generate_key_pair.generateKeyPair('PS256')
console.log(publicKey)
console.log(privateKey)
}
funkcja()

JavaScript Exporting a class definition [duplicate]

This question already has answers here:
Destructuring in Node.JS
(3 answers)
Closed 7 years ago.
Can I export class definition in JavaScript? For example,
in file "HelloWorld.js":
'use strict';
class HelloWorld {
constructor(msg = 'Hello World~') {
this.message = msg;
}
sayHi() {
console.log(this.message);
}
}
module.exports = HelloWorld;
Then in "index.js"
'use strict';
var HelloWorld = require('HelloWorld');
var myObj = new HelloWorld;
myObj.sayHi();
if I do "node index.js", then I got the error below:
constructor(msg = 'Hello World~') {
^
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (/data/users/soltiho/fbsource/fbcode/video_templates/test_env/index.js:3:18)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
my node is v5.5.0
Node doesn't support destructuring (yet), and using destructuring would be wrong anyways. There is nothing special about importing/exporting a class. Import it like any other module:
var myValue = require('myVModule');

Error: cannot find module when testing with mocha

I'm using babeljs to write an RPG engine library. I have two files:
dice.js
import assert from 'assert';
import Random from 'random-js';
export default class Dice {
constructor(maxNumber) {
assert(typeof(maxNumber) === "number", "maxNumber must be a number");
this._mt = Random.engines.mt19937();
this.minNumber = 1;
this.maxNumber = maxNumber;
}
makeThrow() {
this._mt.autoSeed();
return Random.integer(this.minNumber, this.maxNumber)(this._mt);
}
}
throwManager.js
import assert from 'assert';
import Dice from 'dice';
export default class ThrowManager {
constructor(settings) {
assert(settings.hasOwnProperty("numberOfDices"), "must set 'numberOfDices'");
assert(settings.hasOwnProperty("maxNumberInDice"), "must set 'maxNumberInDice'");
assert(settings.maxNumberInDice <= 1, "must have at least 1 dice");
this.settings = settings;
}
execute() {
var throwResults = [];
for (var d = 1; d <= this.settings.numberOfDices; d++) {
var dice = new Dice(this.settings.maxNumberInDice);
throwResults.push(dice.makeThrow());
};
return throwResults;
}
}
When I test them with mocha, I do these imports:
tests.js
var assert = require('assert');
var Amzhen = require('../Amzhen.js');
var random = require('random-js');
//tests here...
Yet when I run the tests, I get this:
Error: Cannot find module 'dice'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/joel/Amzhen.js/Amzhen.js:47:28)
at Module._compile (module.js:456:26)
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 Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/joel/Amzhen.js/test/tests.js:2:14)
Any ideas why the dice module isn't being found?
I'm compiling the code with babel src --out-file Amzhen.js && mocha
You should use:
import Dice from './dice';
'dice' is not the name of a published, installed Node.js module, but a local file, so you should use ./dice with an appropriate path.
See also Module not found error in node.js

Categories