Config TypeScript and Jest + prettier

Config TypeScript and Jest + prettier

First, you need to install typescript package as a dev dependency

npm i -D typescript        

Then install definitely type packages:

npm i -D @types/node        

Now you have to generate `tsconfig.json` file with `npx tsc --init` command. Now you can change the ts configs in the generated `tsconfig.json` file. If you're gonna use `nodemon` in development mode we need to install extra 3rd party dev dependency packages:

npm i -D ts-node rimraf nodemon        

then create a nodemon.js file and write these configurations in it:

{
? "watch": ["src"],
? "ext": ".ts,.js",
? "ignore": [],
? "exec": "ts-node ./src/index.ts"
}        

Add this line in the scripts:

  • "start:dev": "nodemon"
  • "build": "rimraf ./build && tsc"
  • "start": "npm run build && node build/index.js"
  • "test": "jest" (if you want to use jest)

Generate tsconfig.json with this command:

npx tsc --init        

And then update the tsconfig.json file as i did in this picture:

{
? ? "compilerOptions": {
? ? ? ? "target": "es5",
? ? ? ? "module": "commonjs",
? ? ? ? "rootDir": "./src",
? ? ? ? "resolveJsonModule": true,
? ? ? ? "outDir": "./dist",
? ? ? ? "esModuleInterop": true,
? ? ? ? "forceConsistentCasingInFileNames": true,
? ? ? ? "strict": true,
? ? ? ? "skipLibCheck": true,
        "types": [
        ? ? "./global",
        ? ? "jest"
        ]
    }
}        

Jest in Typescript world

you can read their doc for more info:

But here i will make it a little easier to confige it, First you need babel (I think you have the jest already as a dev dependency):

npm i -D babel-jest @babel/core @babel/preset-env @babel/preset-typescript?jest ts-jest @types/jest        

Then you need to configure your babel compiler, so we will create babel.config.js file at the root of our project and write this configurations in it:

module.exports = {
? ? presets: [
? ? ? ? ['@babel/preset-env', { targets: { node: 'current' } }],
?     ? '@babel/preset-typescript',
? ? ],
};
        

Then generate the jest.config.js file by running this command:

npx ts-jest config:init        

Now create test directory at the root of the project and write your test scripts. You can also write your own custom expect functions. To do that you need to implement it first:

expect.extend({
? ? toBeArray(receivedArray: number[], expectedArray: number[]) {
? ? ? ? if (receivedArray.length !== expectedArray.length) {
? ? ? ? ? ? throw new Error("wrong_length");
? ? ? ? }


? ? ? ? for (let tempNumber of expectedArray) {
? ? ? ? ? ? if (typeof tempNumber !== 'number') {
? ? ? ? ? ? ? ? throw new Error(
? ? ? ? ? ? ? ? ? ? "passed_parameter_should_be_number"
? ? ? ? ? ? ? ? );
? ? ? ? ? ? }
? ? ? ? }


? ? ? ? for (let tempNumber of receivedArray) {
? ? ? ? ? ? if (typeof tempNumber !== 'number') {
? ? ? ? ? ? ? ? throw new Error(
? ? ? ? ? ? ? ? ? ? "passed_parameter_should_be_number",
? ? ? ? ? ? ? ? );
? ? ? ? ? ? }
? ? ? ? }


? ? ? ? for (let i = 0; i < expectedArray.length; i++) {
? ? ? ? ? ? if (receivedArray[i] !== expectedArray[i]) {
? ? ? ? ? ? ? ? return {
? ? ? ? ? ? ? ? ? ? pass: false,
? ? ? ? ? ? ? ? ? ? message: () =>
? ? ? ? ? ? ? ? ? ? ? ? `Received array (${receivedArray}) is expected array (${expectedArray})`,
? ? ? ? ? ? ? ? };
? ? ? ? ? ? }
? ? ? ? }


? ? ? ? return {
? ? ? ? ? ? pass: true,
? ? ? ? ? ? message: () =>
? ? ? ? ? ? ? ? `Received array is equal to expected array.`,
? ? ? ? };
? ? },
});        

And finally you need to define it in a type definition file, So to say let's create a jest.d.ts file in the root of the project and copy paste this codes in it:

declare global {
? ? namespace jest {
? ? ? ? interface Matchers<R> {
? ? ? ? ? ? toBeArray(expectedArray: number[]): R;
? ? ? ? }
? ? }
}


export {};        

prettier

Install it as dev dependency or install it globally. finally create its config file at the root of your project:

{
? ? "arrowParens": "always",
? ? "useTabs": false,
? ? "bracketSpacing": true,
? ? "endOfLine": "lf",
? ? "printWidth": 70,
? ? "quoteProps": "as-needed",
? ? "tabWidth": 4,
? ? "trailingComma": "all",
? ? "semi": true,
? ? "singleQuote": true,
? ? "overrides": [
? ? ? ? {
? ? ? ? ? ? "files": "*.yml",
? ? ? ? ? ? "options": {
? ? ? ? ? ? ? ? "singleQuote": false,
? ? ? ? ? ? ? ? "tabWidth": 2
? ? ? ? ? ? }
? ? ? ? }
? ? ]
}        

Add this line in the scripts:

  • "format": "prettier --write '**/*.js' '**/*.ts' '**/*.json'"

tsconfig.json file

If you need to import your own package you can simply use the paths config:

{
    /* ... */
    "paths": {
        "@project-name/auth": [ "./packages/auth" ]
    }
}        

Now you can Import it like this in your codebase:

import { Auth } from '@project-name/auth';        


GitHub repo


Read more:

要查看或添加评论,请登录

Mohammad Jawad barati的更多文章

  • Write test for nanostores

    Write test for nanostores

    why I wrote this post in the first place? Lack of tut and doc around this awesome library that makes our lives easier…

    1 条评论
  • My very own Linux cheat sheet

    My very own Linux cheat sheet

    HAL: Hardware Abstraction Layer do abstract hardwares for us /sys is where we can see what is connected to the system…

    1 条评论
  • ?????? ???? ?? ?????

    ?????? ???? ?? ?????

    ?? ???? ????: ???? ???? 43 ???? ?? (????? ?? ??????) ?? ??? ???? ???? ? ??????? ?????. ??? ??? ??????? ??? 56 ???? ??…

    2 条评论
  • Angular Material UI

    Angular Material UI

    IMO you need to know 3 things before reading this article: Authentication and Authorization in Angular. Whether you…

  • Create Angular project

    Create Angular project

    First please note that the following instructions are totally biased and is my favorite way of doing it. BTW if you…

  • Learn Angular fundamentals.

    Learn Angular fundamentals.

    Note that I am still a backend developer who is dealing with frontend stuff BTW it is not so hard. IMO Angular is much…

  • NestJS task scheduler

    NestJS task scheduler

    To tackle queue issues in NestJS we use @nestjs/schedule. With this package we can define declarative cron jobs.

  • OTP code in Node.js

    OTP code in Node.js

    Send a time-based OTP code - define TTL for the code Keep the symetric keys very safe Use approved cryptographic…

  • Refresh Token + Logout functionality in Node.js

    Refresh Token + Logout functionality in Node.js

    Here is how I implement refresh token in Node.js.

  • My journey in gPRC

    My journey in gPRC

    I am just fooling around gPRC. Please do not count this article as complete right now.

社区洞察

其他会员也浏览了