简体   繁体   中英

DiscordJS Embed Fields imported from another file

So I am attempting to import fields of an embed in a file named fields.js where it contains

const myFields = [
{name: 'something', value: 'something'},
{name: 'something', value: 'something'},
{name: 'something', value: 'something'},
];

module.exports.myFields = myFields;

then in my commandfile.js I am trying to call it like so

const myFields = require('../fields');

const embedTest = new MessageEmbed()
.setColor('#4278f5')
.setTitle('__**MY TITLE**__')
.setThumbnail('mylink.com')
.setDescription(`**something**`)
.addFields([myFields])
.setFooter({text:`my footer`});

I am getting RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty strings

Explanation, read:

In fields.js you exported myFields as part of the module.exports object, not as the default export:

module.exports.myFields = myFields;

This means you are exporting an object which looks like:

{
  myFields: //... etc
}

However, you have imported myFields like this:

const myFields = require('../fields');

Which basically means you are doing this:

const embedTest = new MessageEmbed()
.setColor('#4278f5')
.setTitle('__**MY TITLE**__')
.setThumbnail('mylink.com')
.setDescription(`**something**`)
.addFields([{
  myFields: [
    //... your fields
  ]
}])
.setFooter({text:`my footer`});

Solution

Change the export statement to:

module.exports = myFields;

This sets the myFields array to the default export, rather than enclosing it in an object.

Then you have TWO options. Pick one not both:

1.

Use ... (spread operator) to "spread" the array out. Edit commandfile.js

const myFields = require('../fields');

const embedTest = new MessageEmbed()
.setColor('#4278f5')
.setTitle('__**MY TITLE**__')
.setThumbnail('mylink.com')
.setDescription(`**something**`)
.addFields([...myFields]) // ADD 3 DOTS (spread operator)
.setFooter({text:`my footer`});

2. Recommended

Simply remove the [] surrounding myFields as myFields is the array

const myFields = require('../fields');

const embedTest = new MessageEmbed()
.setColor('#4278f5')
.setTitle('__**MY TITLE**__')
.setThumbnail('mylink.com')
.setDescription(`**something**`)
.addFields(myFields) // removed []
.setFooter({text:`my footer`});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM