Sarah
Sarah

Reputation: 3

Import class from Node.js in normal JavaScript

I have files that use the Node.js framework and other files that I want to implement without using that. When I try to import a class from my node files, where I used module.exports, to my js files, i get the error that "the requested module does not provide an export named default". So is there any way for me to import the node.js class in my JavaScript?

Upvotes: 0

Views: 1367

Answers (1)

Julio Peña
Julio Peña

Reputation: 501

I think only in two methods for solved your problem

METHOD 1

Module1.js

class HelloWorld {
  getHelloWorld() {
    return 'Hello World';
  }
}

module.exports = HelloWorld

Module2.js

const HelloWorld = require('./module1.js');
const helloWorld = new HelloWorld();

METHOD 2 Node <= v12 (Extension file: .msj and run it like node --experimental-modules module2.mjs)

module1.mjs

export default class HelloWorld {
    getHelloWorld() {
        return 'Hello World';
    }
}

module2.msj

import HelloWorld from './module1.mjs';
const helloWorld = new HelloWorld();
console.log(helloWorld.getHelloWorld());

METHOD 2 Node >= v13 (Extension files: .msj or Add { "type": "module" } in the package.json)

module1.mjs or module1.js if you add { "type": "module" } in the package.json

export default class HelloWorld {
    getHelloWorld() {
        return 'Hello World';
    }
}

module2.mjs or module2.js if you add { "type": "module" } in the package.json

import HelloWorld from './module1.mjs';
const helloWorld = new HelloWorld();
console.log(helloWorld.getHelloWorld());

NOTE: If you are interested in knowing the difference between "module.exports vs export default", this topic can help you module.exports vs. export default in Node.js and ES6

Upvotes: 2

Related Questions