Skip to content

Code example requires ES module setup to support top-level await #10932

Open
@Ashish-bbg

Description

@Ashish-bbg

Which application is this bug report for?

Documentation

Issue description

The code example in the documentation uses import and top-level await:

import { REST, Routes } from 'discord.js';

await rest.put(...); 

This throws a SyntaxError unless the project is set up as an ES module, either by:

  • Adding "type": "module" in package.json, or

  • Renaming the file extension to .mjs

Even though the TOP they mentions "Node.js 22.12.0 or newer", that alone isn’t enough — top-level await is only supported in ES modules.

The code example in the documentation (see here) uses import and top-level await:

Suggestion

To run the code exactly as written (using import and top-level await), one of the following changes should be made:

  • Update the documentation to mention that the project must use ES Modules by:
    • Adding "type": "module" to package.json, or
    • Renaming the file to .mjs

OR

  • Change the code example to use CommonJS (require) and wrap the await in an IIFE:
const { REST, Routes } = require('discord.js');

(async () => {
  await rest.put(...);
})();

Steps to Reproduce

  1. Create a new file named deploy-commands.js

  2. Copy the example code from the documentation:

    import { REST, Routes } from 'discord.js';
    
    const rest = new REST({ version: '10' }).setToken('your-token');
    
    await rest.put(Routes.applicationCommands('your-client-id'), {
      body: [{ name: 'ping', description: 'Replies with Pong!' }],
    });
  3. Run the file using Node.js 22+:

     node deploy-commands.js 
  4. Observe the following error:

      SyntaxError: Cannot use import statement outside a module

or

  SyntaxError: await is only valid in async functions and the top level bodies of modules

The code example in the documentation (see here) uses import and top-level await:

Versions

  • Node.js: v22.16.0
  • discord.js: v14.19.3
  • OS: Windows 10

Issue priority

Medium (should be fixed soon)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions