npm init in the folder to setup in.
- Add
typeto package.json and set it tocommonjs. We will be compiling TypeScript to CommonJS for execution, so when node executes the compiled files it should do it as CJS.
discord.js: npm i discord.js @discordjs/rest discord-api-types @discordjs/builders
discord.jsis the main package for connecting to Discord with node.js@discordjs/restto authorise a connection to the Discord APIdiscord-api-typesfor building routes to talk to the Discord API, namely registering application commands.@discordjs/buildersfor helper functions in building Slash commands.
TypeScript: npm i -D typescript @types/node ts-node-dev
typescriptis TypeScript.@types/nodeis typescript definitions for the NodeJS API.ts-node-devallows for incremental compilation of TypeScript code, for faster development.
TypeORM and MySQL: npm i typeorm reflect-metadata mysql2
typeormis TypeORM.reflect-metadatafor access to Decorators.mysql2is the database driver we use for communicating with the database.
Also,
dotenvfor the use of a .env file to store secrets/instance specific setup. The Docker configuration will share this file.
Add a .gitignore file to the root of your project with the following contents:
node_modules/
dist/
.envnode_modules/for the installed packages - don't want these commited to the repo.dist/is where TypeScript should compile to..envwill contain potentially sensitive information.
Add tsconfig.json in the root folder:
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"lib": [ "es6", "es5" ],
"moduleResolution": "node",
"declaration": true,
"outDir": "./dist",
"esModuleInterop": true,
"incremental": true,
"strict": true,
"allowJs": true,
"forceConsistentCasingInFileNames": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"resolveJsonModule": true
},
"include": [ "src/**.ts" ]
}experimentalDecorators and emitDecoratorMetadata as key as they allow us to use TypeORM's decorators! Everything else is up to your discretion - this is my personal tsconfig.
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node-dev --respawn -- src/index.ts"
},We import dotenv and reflect-metadata as soon as we can (top of the file)
import 'dotenv/config';
import 'reflect-metadata';import { Client, Intents } from 'discord.js';
const client = new Client({ intents: [ Intents.FLAGS.GUILDS ] });
client.on('ready', () => {
// Log guilds bot is in on startup
console.log(`Logged in as ${client.user!.tag} and in the following Guilds: [${client.guilds.cache.size}]`);
client.guilds.cache.forEach(g => {
console.log(`[${g.id}] ${g.available ? g.name : "UNAVAILABLE"} `)
});
});
client.login(process.env.TOKEN);