F
F
Flummox_lnc2021-02-15 17:37:20
JavaScript
Flummox_lnc, 2021-02-15 17:37:20

Why does the program crash when importing a function from a file?

In the 'second.js' file I have some function that I am trying to export to the 'main.js' file, here is the code:

//second.js  
export function commandMem(message)
{
  message.channel.send("hello");
}

//main.js
const { MessageEmbed, Client, Channel } = require('discord.js');

const client = new Client();

let text;

import {commandMem} from './second';

client.on('ready', ready => {
  console.log('ready!');
}); 

client.on("message", message => {
text = message.content;
if (text === "test")
{
    commandMem(message); 
}
});

But the editor, without emphasizing anything, gives the following error:
Debugger attached.
(node:9408) 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)
Waiting for the debugger to disconnect...
c:\Users\Михаил\Desktop\Test bot\index.js:7
import {commandMem} from './second';
^^^^^^

I just can’t figure out what could be wrong here, even in Google the exact same code is given as a working one, tell me what is the reason.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Skaarjzzz, 2021-02-15
@Flummox_lnc

Your answer is in error. You need to add the line "type": "module" to package.json so that you can use import, or change export function ... in second.js to

module.exports = {
  commandMem: (message) => { message.channel.send("hello") }
};

And in main js
const { commandMem } = require('./second.js');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question