npm init
in the folder to setup in.
- Add
type
to 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.js
is the main package for connecting to Discord with node.js@discordjs/rest
to authorise a connection to the Discord APIdiscord-api-types
for building routes to talk to the Discord API, namely registering application commands.@discordjs/builders
for helper functions in building Slash commands.
TypeScript: npm i -D typescript @types/node ts-node-dev
typescript
is TypeScript.@types/node
is typescript definitions for the NodeJS API.ts-node-dev
allows for incremental compilation of TypeScript code, for faster development.
TypeORM and MySQL: npm i typeorm reflect-metadata mysql2
typeorm
is TypeORM.reflect-metadata
for access to Decorators.mysql2
is the database driver we use for communicating with the database.
Also,
dotenv
for 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/
.env
node_modules/
for the installed packages - don't want these commited to the repo.dist/
is where TypeScript should compile to..env
will 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);