1

I am more familiar using require() to load CommonJS files into my code. A library I am trying to use requires .mjs file so I am trying to get it to work. I thought it was relatively straight forward but I ran into an issue that I don't know what it is to even search it up.

In my GoogleHomeNotification.js file I have my app defined with 3 seperate functions. Within the same file

App.broadcast("Broadcasting a message");

or any other .js file I can use

const ax = require("../objects/GoogleHomeNotification.js");
ax.broadcast("Test");

Now in my test.mjs file I have

import * as GoogleNotification from "../objects/GoogleHomeNotification.js"
GoogleNotification.broadcast("Test");

and when I try to compile and run it, I get

TypeError: GoogleNotification.broadcast is not a function.

A nudge in the right direction of what I should be learning/searching for would be greatly appreciated!

GoogleHomeNotification.js:

var App = {
    playin: false,
    DeviceIp: "",
    OriginalVolume: .5,
    Player: null,
    GoogleHome: function (host, url, callback) {},
    run: function (ip, text) {},
    broadcast: function(text){}
};
module.exports = App;

EDIT: Node version 14.15.4

1
  • What were they thinking? Couldn't import just have been a synonym for require in the interim. :( The .mjs thing bytes my bits. Commented Aug 6, 2024 at 20:22

1 Answer 1

1

This should work

import { default as GoogleNotification } from "../objects/GoogleHomeNotification.js";

Or if you dont need the alias, then just use

import App from "../objects/GoogleHomeNotification.js";
Sign up to request clarification or add additional context in comments.

2 Comments

I don't need the alias for right now so the second option works, but I am curious as to why the original import didn't? Thank you by the way!
That is because when you use import * from... you import the whole module. Your export statement is equivalent to export default App; So if you want, you should use it like this GoogleNotification.default.broadcast("message");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.