Why is an error popping up when the import has already been executed successfully?

Description

When attempting to execute my code, I encountered an issue. I made several changes to my tsconfig in hopes of resolving it, but now I can't remember what modifications I made. Any insights on this matter would be greatly appreciated!

The package ts-node-dev is being used to run the code.

Main.ts

This is the primary TypeScript code that is executed first:

import { ShardingManager } from 'discord.js';
import { client } from '../config/config';
import chalk from 'chalk';

const manager = new ShardingManager(__dirname + '/client.ts', { token: client.token });

manager.on('shardCreate', (shard) => console.log(chalk.magenta(`[SHARD MANAGER]`), `Launched shard ${shard.id}`));

manager.spawn();

Client.ts

Here is the client.ts code that is managed by the sharding manager:

import { Client as DiscordClient, Intents } from 'discord.js';
import { client } from '../config/config';

const Client = new DiscordClient({ intents: [Intents.FLAGS.GUILDS] });

Client.on('interactionCreate', (interaction) => {
  if (!interaction.isCommand()) return;

  const { commandName } = interaction;

  if (commandName === 'stats') {
    return Client.shard
      .fetchClientValues('guilds.cache.size')
      .then((results) => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        return interaction.reply(`Server count: ${results.reduce((acc, guildCount) => acc + guildCount, 0)}`);
      })
      .catch(console.error);
  }
});

Client.login(client.token);

Error

Below is the error message I am encountering:

/workspace/Hez/src/client/client.ts:1
import { Client as DiscordClient, Intents } from 'discord.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.nodeDevHook [as .js] (/workspace/Hez/node_modules/ts-node-dev/lib/hook.js:63:13)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/workspace/Hez/node_modules/ts-node-dev/lib/wrap.js:104:1)
[ERROR] 16:20:04 SyntaxError: Cannot use import statement outside a module

Package.json

{
  "devDependencies": {
    "@discordjs/builders": "^0.9.0",
    "@discordjs/rest": "^0.2.0-canary.0",
    "@types/express": "^4.17.13",
    "@types/node": "^17.0.2",
    "@typescript-eslint/eslint-plugin": "^5.8.0",
    "@typescript-eslint/parser": "^5.8.0",
    "discord-api-types": "^0.25.2",
    "discord.js": "^13.3.1",
    "eslint": "^8.5.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "express": "^4.17.2",
    "mongoose": "^6.1.2",
    "prettier": "^2.5.1",
    "ts-node": "^10.4.0",
    "ts-node-dev": "^1.1.8",
    "typescript": "^4.5.4"
  },
  "dependencies": {
    "chalk": "4.1.2"
  },
  "name": "",
  "description": "",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "none",
    "start": "ts-node src/start.ts",
    "dev": "ts-node-dev src/start.ts",
    "watch": "npx tsc",
    "prettier-format": "prettier --config .prettierrc 'src/**/*.ts' --write",
    "lint": "eslint . --ext .ts"
  },  "keywords": [],
  "author": "",
  "license": "ISC",
}

Answer №1

The problem arose with the ts-node-dev package - switching to the regular TypeScript compiler resolved it!

Answer №2

const Manager = new ShardingManager('./bot.ts', {token, execArgv: ['-r', 'ts-node/register']});

This solution worked perfectly for me after implementing the execArgv option.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a TypeScript type or interface that represents an object with one of many keys or simply a string

I am tasked with creating an interface that can either be a string or an object with one of three specific keys. The function I have takes care of different errors and returns the appropriate message: export const determineError = (error: ServerAlerts): ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...

Designate as a customizable class property

I'm struggling to create a versatile inheritance class for my services. Currently, I have two service classes named Service_A and Service_B that essentially do the same thing. However, Service_A works with Class_A while Service_B works with Class_B. T ...

Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs. Although the code works flawlessly when I manually s ...

Tips for maintaining the menu state following a refresh

Is there a way to save the menu state when pressing F5? I'm looking for a similar functionality as seen on the Binance website. For example, clicking on the Sell NFT's submenu and then refreshing the page with F5 should maintain the menu state on ...

Perform an Angular HTTP request and await responses from multiple sources

I'm currently working with Angular 11 and looking to make an HTTP call to an API that will trigger a server-side process. Here's the code for the HTTP call: processData(data) { return this.httpClient.post('https://myurl/api/process&apos ...

Stopping npm build when ESLint detects warnings

Dealing with a particularly immature team, I am determined to make the react-typescript build fail whenever ESLint issues warnings. src/modules/security/components/ForgotPasswordBox/index.tsx Line 8:18: 'FormikHelpers' is defined but never use ...

Using TypeScript TSX with type parameters

Is it possible to define type parameters in TypeScript TSX syntax? For instance, if I have a class Table<T>, can I use something like <Table<Person> data={...} /> ...

Utilize Typescript to ensure uniformity in object structure across two choices

Looking to create a tab component that can display tabs either with icons or plain text. Instead of passing in the variant, I am considering using Typescript to verify if any of the icons have an attribute called iconName. If one icon has it, then all othe ...

The issue with sorting in Angular 8 mat tables persists when dealing with multiple tables

As a newcomer to Angular, I am still learning and have encountered an issue with sorting in the mat table. I have multiple tables on one page, each separated by a mat tab. The problem is that sorting only works on the first table ("crane master list") in t ...

Unable to utilize Component Selectors with MUI v5 and Emotion Library

import { Box, styled } from "@mui/material" import { Body1 } from "elements/Typography" export const ItemHeader = styled(Box)` display: flex; flex-direction: column; gap: 1em; ${Body1} { span { margin-left: 0.5em; ...

Having trouble launching React application on local machine due to missing node modules

I am completely new to React. I recently forked a project on Github and am attempting to run it on my own machine. However, I've noticed that the folder structure is missing the node modules. Does this mean I need to install create-react-app globally ...

Avoid including any null or undefined values within a JSON object in order to successfully utilize the Object.keys function

My JSON data structure appears as follows: { 'total_count': 6, 'incomplete_results': false, 'items': [ { 'url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2', 'repository_url' ...

Tips for retrieving a cropped image with Croppr.js

Currently, I am developing a mobile application using Ionic 3. Within the application, I have integrated the Croppr.js library to enable image cropping before uploading it to the server. However, I am facing an issue where I am unable to retrieve the cropp ...

Tips on passing an object as data through Angular router navigation:

I currently have a similar route set up: this.router.navigate(["/menu/extra-hour/extra-hours/observations/", id]) The navigation is working fine, but I would like to pass the entire data object to the screen in order to render it using the route. How can ...

Attaching a function to a designated slot attribute

Currently, I am utilizing VUE 2.6.11 along with class components. My current objective involves encapsulating components that can serve as modals inside a separate component responsible for managing the modal state. According to the documentation, it is p ...

Reacting like sticky bottoms and tops

I'm working on a react/tailwind project that involves a component I want to be fixed at both the top and bottom of the screen. In simpler terms, there's an element that I need to always stay visible even when the user scrolls up or down the page ...

What could be causing my Angular2 component to not properly use my template?

I have two components that I am working with. The first component is: import {Component} from 'angular2/angular2'; import {Navbar} from './navbar'; @Component({ selector: 'app' template: `<div class="col-md-12"> ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Eliminating tail recursion for conditional types is ineffective

In TypeScript version 4.5, the feature of tail call optimization was introduced for recursive generics. The code snippet below calculates Fibonacci numbers (in unary) up to F12, but encounters an error when trying to compute F13 due to the "Type instantiat ...