I am new to Typescript and I am trying to convert my Js code to ts

I have the base bot set up already in Javascript like the command handling and the main file and when I asked if I could use Typescript with my bot they said It should just work fine if I convert my code. When I did this I found out I needed a tsconfig.json and now I was getting a lot of Include and Exclude errors etc. I just use the basic one could somebody help me tsc --init Its in my root directory and my main is in Root/src/bot.ts. Just somebody help me set it up.
9 Replies
d.js toolkit
d.js toolkit•12mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button!
d.js docs
d.js docs•12mo ago
To share long code snippets, use a service like gist, sourcebin, starbin, or similar instead of posting them as large code blocks or files.
Ceymikey 🎗
Ceymikey 🎗OP•12mo ago
Gist
tsconfig.json
GitHub Gist: instantly share code, notes, and snippets.
Ceymikey 🎗
Ceymikey 🎗OP•12mo ago
Could you help me with this
import * as fs from 'fs';
^^^^^^

SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1175:20)
at Module._compile (node:internal/modules/cjs/loader:1219:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47

Node.js v20.2.0
import * as fs from 'fs';
^^^^^^

SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1175:20)
at Module._compile (node:internal/modules/cjs/loader:1219:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47

Node.js v20.2.0
const { Client, Intents, Collection } = require('discord.js');
import * as fs from 'fs';

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

client.commands = new Collection();

require('dotenv').config();

const functions = fs.readdirSync('./src/functions').filter((file: string) => file.endsWith('.js'));
const eventFiles = fs.readdirSync('./src/events').filter((file: string) => file.endsWith('.js'));
const commandFolders = fs.readdirSync('./src/commands');

(async () => {
for (const file of functions) {
require(`./functions/${file}`)(client);
}

client.handleEvents(eventFiles, './src/events');
client.handleCommands(commandFolders, './src/commands');

await client.login(process.env.token);
})();
const { Client, Intents, Collection } = require('discord.js');
import * as fs from 'fs';

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

client.commands = new Collection();

require('dotenv').config();

const functions = fs.readdirSync('./src/functions').filter((file: string) => file.endsWith('.js'));
const eventFiles = fs.readdirSync('./src/events').filter((file: string) => file.endsWith('.js'));
const commandFolders = fs.readdirSync('./src/commands');

(async () => {
for (const file of functions) {
require(`./functions/${file}`)(client);
}

client.handleEvents(eventFiles, './src/events');
client.handleCommands(commandFolders, './src/commands');

await client.login(process.env.token);
})();
can
can•12mo ago
can do it with bun js
can
can•12mo ago
Bun
Module resolution – Runtime | Bun Docs
Bun uses ESM and implements an extended version of the Node.js module resolution algorithm.
Kinect3000
Kinect3000•12mo ago
So you are using bun? You shouldn’t be running w/ node.js if you are
Ceymikey 🎗
Ceymikey 🎗OP•12mo ago
Could somebody help me resolve this other Issue I am having. After translating all of my code/Handlers etc and using the typescript compiler its saying require isn't a function is this because I need to use import in my ts file??
PS C:\ADMINS\Harper> npm start

> node src/test/bot.js

C:\ADMINS\Harper\src\test\bot.js:29
require('./functions/handleEvents')(client);
^

TypeError: require(...) is not a function
at Object.<anonymous> (C:\ADMINS\Harper\src\test\bot.js:29:36)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47

Node.js v20.2.0
PS C:\ADMINS\Harper> npm start

> node src/test/bot.js

C:\ADMINS\Harper\src\test\bot.js:29
require('./functions/handleEvents')(client);
^

TypeError: require(...) is not a function
at Object.<anonymous> (C:\ADMINS\Harper\src\test\bot.js:29:36)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47

Node.js v20.2.0
My code snippet: https://gist.github.com/Ceymikey/4173d428ace844fd257feff1c94a13c9
Gist
The main file for my Discord ts bot
The main file for my Discord ts bot. GitHub Gist: instantly share code, notes, and snippets.
Ceymikey 🎗
Ceymikey 🎗OP•11mo ago
My compiled js file is just a bunch of code for nodejs shouldn;t be anything to worry about I've also put it in the same folder to not get any path not found conflicts (Both in src folder) Nope If you meant me.
import { Client } from 'discord.js';

interface Event {
name: string;
once: boolean;
execute: (...args: any[]) => void;
}

const handleEvents = async (client: Client, eventFiles: string[], path: string): Promise<void> => {
for (const file of eventFiles) {
const event: Event = require(`../events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
};

export default handleEvents;
import { Client } from 'discord.js';

interface Event {
name: string;
once: boolean;
execute: (...args: any[]) => void;
}

const handleEvents = async (client: Client, eventFiles: string[], path: string): Promise<void> => {
for (const file of eventFiles) {
const event: Event = require(`../events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
};

export default handleEvents;
I tried to find a way with import but I don't know how it could be done But do I just completely remove the (client) Wait let me reopen my code before I start talking I tried this
import { Client, Intents, Collection } from 'discord.js';
import fs from 'fs';
// Importing handleEvents from here
import handleEvents from './functions/handleEvents';

export interface CommandType {
data: {
name: string;
description: string;
options?: Array<{ name: string; description: string; type: number; required?: boolean }>;
};
execute: (...args: any[]) => void;
}

// Extend the existing Client type
interface ExtendedClient extends Client {
commands: Collection<string, CommandType>;
}

// Create a constructor function to initialize the ExtendedClient
const createExtendedClient = (): ExtendedClient => {
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] }) as ExtendedClient;
client.commands = new Collection<string, CommandType>(); // Specify the type for the Collection
return client;
};

const client = createExtendedClient();

require('dotenv').config();

const functions = fs.readdirSync('./src/functions').filter((file) => file.endsWith('.ts'));
const eventFiles = fs.readdirSync('./src/events').filter((file) => file.endsWith('.ts'));
const commandFolders = fs.readdirSync('./src/commands');

// Uses the handleEvents function here
handleEvents(client);

(async () => {
for (const file of functions) {
require(`./functions/${file}`)(client);
}

// Assuming you have a similar function for handling commands
const handleCommands = require('./functions/handleCommands');
await handleCommands.default(client, commandFolders, './src/commands');

await client.login(process.env.token);
})();
import { Client, Intents, Collection } from 'discord.js';
import fs from 'fs';
// Importing handleEvents from here
import handleEvents from './functions/handleEvents';

export interface CommandType {
data: {
name: string;
description: string;
options?: Array<{ name: string; description: string; type: number; required?: boolean }>;
};
execute: (...args: any[]) => void;
}

// Extend the existing Client type
interface ExtendedClient extends Client {
commands: Collection<string, CommandType>;
}

// Create a constructor function to initialize the ExtendedClient
const createExtendedClient = (): ExtendedClient => {
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] }) as ExtendedClient;
client.commands = new Collection<string, CommandType>(); // Specify the type for the Collection
return client;
};

const client = createExtendedClient();

require('dotenv').config();

const functions = fs.readdirSync('./src/functions').filter((file) => file.endsWith('.ts'));
const eventFiles = fs.readdirSync('./src/events').filter((file) => file.endsWith('.ts'));
const commandFolders = fs.readdirSync('./src/commands');

// Uses the handleEvents function here
handleEvents(client);

(async () => {
for (const file of functions) {
require(`./functions/${file}`)(client);
}

// Assuming you have a similar function for handling commands
const handleCommands = require('./functions/handleCommands');
await handleCommands.default(client, commandFolders, './src/commands');

await client.login(process.env.token);
})();
But there seems to be a mistake in my code still. Than I remove (client) from the end And now I am resolving other issues. Should I be worried about this? It was showing red and saying An argument for evenfiles was not provided Alright Is this because I had set my module to ES6 When I switched everything I got like 15 more errors but await was working v20.2.0 Do you recommend upgrading to v21+ Or what module should I use With what target I use es2022 as a target right now. i am facing other issues now with the ts compiler.
node:internal/modules/cjs/loader:1073
throw err;
^

Error: Cannot find module '../functions/handleEvents'
Require stack:
- C:\Users\admin\OneDrive\Bureaublad\Harper\src\test\bot.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1070:15)
at Module._load (node:internal/modules/cjs/loader:923:27)
at Module.require (node:internal/modules/cjs/loader:1137:19)
at require (node:internal/modules/helpers:121:18)
at Object.<anonymous> (C:\Users\admin\OneDrive\Bureaublad\Harper\src\test\bot.js:18:40)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\admin\\OneDrive\\Bureaublad\\Harper\\src\\test\\bot.js'
]
}
node:internal/modules/cjs/loader:1073
throw err;
^

Error: Cannot find module '../functions/handleEvents'
Require stack:
- C:\Users\admin\OneDrive\Bureaublad\Harper\src\test\bot.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1070:15)
at Module._load (node:internal/modules/cjs/loader:923:27)
at Module.require (node:internal/modules/cjs/loader:1137:19)
at require (node:internal/modules/helpers:121:18)
at Object.<anonymous> (C:\Users\admin\OneDrive\Bureaublad\Harper\src\test\bot.js:18:40)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\admin\\OneDrive\\Bureaublad\\Harper\\src\\test\\bot.js'
]
}
I am sure the path is correct but just to be sure. My code: https://gist.github.com/Ceymikey/05625bbe4077fb3e9f82d0306cccdffb Tsc Javascript code: https://gist.github.com/Ceymikey/6978485d4c3723616812f2f5d9a5b206 Also just to clear up some things. I used the require function because I changed my exports default to a module.exports in my handleEvents. And here is my path Was I support to require my handleEvents.js that came out of the tsc or my handleEvents.ts? Oh oke I was thinking it would conflict my paths if I did that. I thought the tsc only converts code to js that node understands and doesn't change anything. Its giving me that same error tho:
node:internal/modules/cjs/loader:1073
throw err;
^

Error: Cannot find module '../src/functions/handleEvents'
Require stack:
- C:\Users\admin\Harper\test\bot.js
node:internal/modules/cjs/loader:1073
throw err;
^

Error: Cannot find module '../src/functions/handleEvents'
Require stack:
- C:\Users\admin\Harper\test\bot.js
Its in my Utils folder So your telling me I was instead of the dist or test folder suppost to put it in the same folder as my bot.ts? So in utils Error: Cannot find module './src/functions/handleCommands.ts' This is from bot.js
PS C:\Users\admin\OneDrive\Bureaublad\Harper> npm start

> node src/utils/test/bot.js

node:internal/modules/cjs/loader:1070
const err = new Error(message);
^

Error: Cannot find module './src/functions/handleCommands.ts'
Require stack:
- C:\Users\admin\OneDrive\Bureaublad\Harper\src\utils\test\bot.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1070:15)
at Module._load (node:internal/modules/cjs/loader:923:27)
at Module.require (node:internal/modules/cjs/loader:1137:19)
at require (node:internal/modules/helpers:121:18)
at C:\Users\admin\OneDrive\Bureaublad\Harper\src\utils\test\bot.js:21:9
at Object.<anonymous> (C:\Users\admin\OneDrive\Bureaublad\Harper\src\utils\test\bot.js:32:3)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\admin\\OneDrive\\Bureaublad\\Harper\\src\\utils\\test\\bot.js'
]
}

Node.js v20.2.0
PS C:\Users\admin\OneDrive\Bureaublad\Harper> npm start

> node src/utils/test/bot.js

node:internal/modules/cjs/loader:1070
const err = new Error(message);
^

Error: Cannot find module './src/functions/handleCommands.ts'
Require stack:
- C:\Users\admin\OneDrive\Bureaublad\Harper\src\utils\test\bot.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1070:15)
at Module._load (node:internal/modules/cjs/loader:923:27)
at Module.require (node:internal/modules/cjs/loader:1137:19)
at require (node:internal/modules/helpers:121:18)
at C:\Users\admin\OneDrive\Bureaublad\Harper\src\utils\test\bot.js:21:9
at Object.<anonymous> (C:\Users\admin\OneDrive\Bureaublad\Harper\src\utils\test\bot.js:32:3)
at Module._compile (node:internal/modules/cjs/loader:1255:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module._load (node:internal/modules/cjs/loader:960:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\admin\\OneDrive\\Bureaublad\\Harper\\src\\utils\\test\\bot.js'
]
}

Node.js v20.2.0
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const discord_js_1 = require("discord.js");
const fs_1 = __importDefault(require("fs"));
// Create a constructor function to initialize the ExtendedClient
const createExtendedClient = () => {
const client = new discord_js_1.Client({ intents: [discord_js_1.Intents.FLAGS.GUILDS, discord_js_1.Intents.FLAGS.GUILD_MESSAGES] });
client.commands = new discord_js_1.Collection(); // Specify the type for the Collection
return client;
};
const client = createExtendedClient();
require('dotenv').config();
const functions = fs_1.default.readdirSync('./src/functions').filter((file) => file.endsWith('.ts'));
const eventFiles = fs_1.default.readdirSync('./src/events').filter((file) => file.endsWith('.ts'));
const commandFolders = fs_1.default.readdirSync('./src/commands');
(async () => {
for (const file of functions) {
require(`./src/functions/${file}`)(client);
}

// Assuming you have a similar function for handling commands
const handleCommands = require(`./src/functions/handleCommands`).default;
await handleCommands(client, commandFolders, './src/commands');

const handleEvents = require(`./src/functions/handleEvents`).default;
await handleEvents(client, eventFiles, './src/events');

await client.login(process.env.token);
})();
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const discord_js_1 = require("discord.js");
const fs_1 = __importDefault(require("fs"));
// Create a constructor function to initialize the ExtendedClient
const createExtendedClient = () => {
const client = new discord_js_1.Client({ intents: [discord_js_1.Intents.FLAGS.GUILDS, discord_js_1.Intents.FLAGS.GUILD_MESSAGES] });
client.commands = new discord_js_1.Collection(); // Specify the type for the Collection
return client;
};
const client = createExtendedClient();
require('dotenv').config();
const functions = fs_1.default.readdirSync('./src/functions').filter((file) => file.endsWith('.ts'));
const eventFiles = fs_1.default.readdirSync('./src/events').filter((file) => file.endsWith('.ts'));
const commandFolders = fs_1.default.readdirSync('./src/commands');
(async () => {
for (const file of functions) {
require(`./src/functions/${file}`)(client);
}

// Assuming you have a similar function for handling commands
const handleCommands = require(`./src/functions/handleCommands`).default;
await handleCommands(client, commandFolders, './src/commands');

const handleEvents = require(`./src/functions/handleEvents`).default;
await handleEvents(client, eventFiles, './src/events');

await client.login(process.env.token);
})();
mmLol fixing paths in my code I am really just starting to think Typescript is messing up my paths Because in my ts code I did them correct And they are both the same
src/bot.ts
dist/bot.js
src/bot.ts
dist/bot.js
Idk what I am doing wrong ¯\_(ツ)_/¯ I compile my code and run the js cuz node cannot directly run ts code.
"scripts": {
"build": "tsc --watch",
"start": "node dist/bot.js",
"test": "node dist/bot.js"
},
"scripts": {
"build": "tsc --watch",
"start": "node dist/bot.js",
"test": "node dist/bot.js"
},
Found it I think As you said I was pointing all to my src folder ts files but now bot.ts its functions etc is pointing to src and my bot.js is pointing to all the stuff inside of my dist folder. Handling js in dist handling ts in dist meguFace starting succesfully But isn't doing anything No console log events No slash commands So ig I still messed up some path It was because it stated endswith .ts and not .js is there a way for me to make it so that the tsc also changes that So when I compile it .ts changes to .js Or could I use something like .* Its in my main file
Want results from more Discord servers?
Add your server