提问者:小点点

VSCode 中的错误,当我尝试创建一个 Spotify 不和谐机器人时:[ 语法错误:无法在模块外部使用导入语句 ] 与节点.js [重复]


我不能执行和调试我的不和谐机器人,调试控制台出错。

这是我在机器人中的代码:

const discord = require('discord.js');
const client = new discord.Client({
    ws: { intents: discord.Intents.ALL },
});

import spotify from 'spotify-web-api-js';
const spotifyAPI = new spotify();

import { MessageEmbed } from 'discord.js';

//Spotify Credentials
spotifyAPI.setAccessToken('HIDDEN');

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', message => {
    if (message.content.startsWith('!play')) {
        let songName = message.content.split(" ").slice(1).join(" ");
        spotifyAPI.searchTracks(songName)
        .then(function(data) {
            let song = data.tracks.items[0];
            let songName =song.name;
            let songUrl =song.preview_url;
            let songAuthor =song.artists[0].name;
            let songEmbed = new MessageEmbed()
            .setTitle(`Playing ${songName}`)
            .setURL(songUrl)
            .setAuthor(songAuthor)
            .setColor('#0099ff')
            message.channel.send(songEmbed);
        }, function(err) {
            console.error(err);
            message.channel.send("Sorry, I couldn't find the song you requested. Please try again with a different name or check your internet connection.");
        });
    }
});

client.login('HIDDEN');

我的调试控制台中出现了这个错误:

Uncaught SyntaxError C:\Users\MY_USERNAME\Proyectos de VS Code\spoticord\spoticord.js:6
import spotify from 'spotify-web-api-js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at compileFunction (vm:360:18)
    at wrapSafe (internal/modules/cjs/loader:1088:15)
    at Module._compile (internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (internal/modules/cjs/loader:1213:10)
    at Module.load (internal/modules/cjs/loader:1037:32)
    at Module._load (internal/modules/cjs/loader:878:12)
    at executeUserEntryPoint (internal/modules/run_main:81:12)
    at <anonymous> (internal/main/run_main_module:23:47)
Process exited with code 1

我试过更新discord.js,spotify-web-api-js,重装两个模块。但是给出了另一个错误,如:

    < li>TypeError:无法读取undefined的属性(读取“ALL”) < li >语法错误:标识符“Discord”已经声明 < li >必须为客户提供有效的意向。

共1个答案

匿名用户

当<code>导入</code>用于“模块”类型时,您的包的设置是针对“CommonJS”的。

// at line 6
import spotify from 'spotify-web-api-js'
// at line 9
// this must be replaced also, like at line 6
import { MessageEmbed } from 'discord.js';

有两个正确的解决方案。

    < li >在“package.json”中将“type”设置为“module ”,并使用< code>import