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)
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