-1

I have in my website a class named classPerson which is in dir /foo. I need to use it in dir ./bar, but since /bar is not allowed to import from /foo i do the following:

/foo:

  const classPerson = new classPerson();

  Object.assign(window, { classPerson });

/bar:

const person = window.classPerson.

I need to achieve a similar thing in node.js. How can i do it (having no window)

YTG
  • 956
  • 2
  • 6
  • 19
  • There is [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis). – trincot Jul 17 '22 at 06:24
  • since 2019 you can use `globalThis` (which you can also do instead of `window`) - browser: `globalThis === window` .... node: `globalThis === global` – Jaromanda X Jul 17 '22 at 06:24
  • 1
    Why is `bar` not allowed to import from `foo`? That's your main problem here. You shouldn't be looking to use globals in nodejs. Instead, you should learn how to use modularity and import/export properly. – jfriend00 Jul 17 '22 at 06:30

1 Answers1

0

Depending on your project setup, you can use either the built-in require() method or the es6 import module syntax.

in /foo.js

export class ClassPerson { ... } // add the export keyword to the class definition

export const classPersonInstance = new classPerson(); // add the export keyword to the class instance if you want to use the same instance

in /bar.js

const foo = require('./foo.js');
const instance = foo.classPersonInstance;

// or
import { classPersonInstance } from './foo.js';

NOTE To be able to use the import syntax, you should do some additional configuration

Here is the nodejs documentation for ECMAScript Modules

Sadra M.
  • 1,304
  • 1
  • 17
  • 28
  • Thanks for answering! please read my question again, i cant import. I want to achieve it similar to the code i posted, doing the same idea, not to import – YTG Jul 17 '22 at 06:37
  • @YTG No probs! if this answer wokred for you, please take the time to accept this answer by ticking the check icon on the left. – Sadra M. Jul 17 '22 at 06:38