Code Review Videos > Learn TypeScript > TypeScript Project Setup

TypeScript Project Setup

The following steps set up a bare bones TypeScript project that is suitable for writing code in TypeScript and testing code using Jest.

mkdir -p my-test-project/src cd my-test-project npm init --yes npm i -D @types/jest @types/node jest prettier ts-jest typescript npx tsc --init npx ts-jest config:init
Code language: Shell Session (shell)

That should set you up with:

ls -bp1 jest.config.js node_modules/ package.json package-lock.json src/ tsconfig.json

I would also then edit package.json as follows:

"scripts": { "start:tsc": "tsc -w", "test": "jest", "test:watch": "jest --watchAll --runInBand --coverage" },
Code language: JSON / JSON with Comments (json)

This will allow me to run:

  • npm run test:watch
    from the command line and get Jest to run as I code
  • npm run start:tsc
    from the command line and make TypeScript compile the source code to JS in real time / on save

One other change I make, which is not mandatory but one that I personally like is to set TypeScript to build code to a different directory than the source TS files:

// tsconfig.json { "compilerOptions": { "target": "es2016", "module": "commonjs", "outDir": "./dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true }, "exclude": [ "node_modules", "**/*.spec.ts" ] }
Code language: JSON / JSON with Comments (json)

Assuming you then create a file at src/index.ts, the compiler will spit out a dist/index.js file, and so on.

If you go with this approach, ensure you exclude the outDir path from the list of directories that Jest will look in to find your tests:

// jest.config.js /** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { preset: "ts-jest", testEnvironment: "node", testPathIgnorePatterns: ["./dist"], };
Code language: JavaScript (javascript)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: