Setting up a simple project with Express JS using Typescript and Gulp JS.

 

Setting up a simple project with Express JS using Typescript and Gulp JS.

What we will cover:

  • Setting up NPM dependencies for our projects
  • Setting up gulpfile

  • Setting up tsconfig file.

  • Setting up default tslint file.

  • Spinning up a simple Express server and displaying a message.

Setting Up Our package.json:


{
  "name": "express-bootstrap",
  "version": "1.0.0",
  "description": "Typescript-express-boilerplate",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "gulp scripts",
    "watch": "gulp watch",
    "start": "concurrently \"npm run watch\" \"nodemon dist/index.js\""
  },
  "author": "Kody Bentley",
  "license": "MIT",
  "dependencies": {
    "@types/express": "^4.0.39",
    "@types/gulp": "^4.0.5",
    "concurrently": "^3.5.1",
    "express": "^4.16.2",
    "gulp": "^3.9.1",
    "gulp-typescript": "^3.2.3",
    "nodemon": "^1.13.3",
    "tslint": "^5.8.0",
    "typescript": "^2.6.2"
  }
}

Lets Break This Down:

  • Here we are defining a pretty standard package json file for our project, complete with dependencies that will be needed, as well as some scripts we will be able to run through npm.

  • Once we have the package json file in the root of our directory we can run a simple “npm install”, in terminal to install all appropriate npm packages.

  • We will not be going into extreme detail for setting up a project using NPM since this tutorial is focused more on Express-Typescript instead of basic npm projects.

Setting Up Our tsconfig.json:


{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

Lets Break This Down:

  • Same as with the package json file we are defining a pretty out of the box basic tsconfig file in our root of the directory

  • We set our compilerOptions to target es6 as well as our module to be commonjs, there are other options you can pass here but this is what we will use for this tutorial and seems to be pretty standard. For more details on how to customize tsconfig take a look at their fantastic docs found here https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

  • The only other two things we will pass in our tsconfig is going to be our “include” which will be what files we want typescript to include in our case we will pass all Typescript files found in our source folder. For “exclude” we will simply have all of our node_modules excluded.

Setting up our tslint.json


{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {},
    "rulesDirectory": []
}

Lets Break This Down:

  • This is basically just a standard tslint json in the root of our directory, for this project we will not be going into to much detail about the features or power of tslint, we will however be including it in our project for later use if wanted. For more information take a look at the docs here https://palantir.github.io/tslint/usage/tslint-json/

Setting up our gulpfile.js:


const gulp = require('gulp');
const ts = require('gulp-typescript');

// pull in the project TypeScript config
const tsProject = ts.createProject('tsconfig.json');

gulp.task('scripts', () => {
  const tsResult = tsProject.src()
    .pipe(tsProject());
  return tsResult.js.pipe(gulp.dest('dist'));
});

gulp.task('watch', ['scripts'], () => {
  gulp.watch('src/**/*.ts', ['scripts']);
});

Lets Break This Down:

  • We will create a gulpfile.js in the root of our directory.

  • Starting at the top we will define some const variables to contain gulp, as well as gulp-typescript, and one to create our project from our tsconfig file.

  • Next we will run a gulp task called ‘scripts’, set our tsResult to tsProject.src(), then pipe tsProject() and return our result pipe to our gulp.dest which in our case will be a folder in our root called ‘dist’.

  • Our final gulp task called ‘watch’, will call ‘scripts’ anytime its triggered, we set our gulp watcher to any typescript file in our src folder. Basically anytime a Typescript file is changed in source the watch will trigger our ‘scripts’ and recompile our Typescript into javascript in our dist to be served.

Creating folder structure for project:

  • So far every file we have gone over is located in the root of our directory.

  • We need to create two new folders, one called ‘src’ which will contain all of our Typescript files we will be working on, as well as a ‘dist’ folder which will contain our javascript files that were compiled from Typescript, these are the files that will be served to the browser.

Setting up our index.ts and Express:



import * as express from 'express';

export default class Server {
    private _app: express.Express = express();

    constructor(){
        this.init();
    }

    init(){
        this._app.listen(3000, () => {
            console.log("Example app listening on port 3000!")
          });

          this._app.get('/', (req, res) => {
            res.json({
                message: "Hello World!"
            });
          })
    }
}

new Server();

Lets Break This Down:

  • First thing we do in our index.ts file is we want access to Express, we will do this by importing the Express module from our node_modules.

  • Secondly we setup our class which in this case we will be calling it Server, inside our of class the first thing we do is set a private variable called _app which is of type express, and contains express();

  • Thirdly we setup our constructor, for this simple project the only thing we will be initializing is going to be a function we have called init();

  • Next inside our of init function we will call expresses listen function, we will pass it the port we want, which is going to be port 3000, then an anonymous function that when is triggered will console log that we are listening on port 3000.

  • Finally we want to display a message when we are connected to port 3000 with our express server. We do this by calling expresses get functionality. We pass ‘/’ for our root, then an anonymous function which accepts our request, and response, once this function is triggered we will call expresses response json and pass a message which will be “Hello World”;

  • Last but not least we initialize our Server by calling new Server(); at the end of the file.

  • In terminal run our premade npm script from our package json called “npm start”, if all was done successfully you should see this in terminal

as well as this in your browser when you go to localhost:3000

Quick note on our npm start:


"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "gulp scripts",
    "watch": "gulp watch",
    "start": "concurrently \"npm run watch\" \"nodemon dist/index.js\""
  }

Lets Break This Down:

  • Just some quick notes on what is happening when we call our npm start script
  • If you take a look at the scripts above npm start is going to concurrently run our npm run watch which is our gulp watch function that we defined in the gulpfile, it also runs nodemon on our index.js file located inside of our dist folder. Using nodemon means we dont have to restart our server everytime there is a change for us to see it.

Conclusion:

  • We learned how to set up a package json file for our express/typescript project.

  • We learned how to set up tsconfig for our project.

  • We learned how to set up a gulpfile for our project.

  • We learned how to create a Server class for express in typescript and connect and display content in the browser.

  • Feel free to clone the entire project off of github found here¬†https://github.com/KodyBentley/express-typescript-boilerplate

Thank you very much for reading. Please stay tuned for upcoming tutorials.