- Install nvm
- Install Node.js v8 by using nvm
- Install JetBrains (optional)
- Clone the repository
git clone --depth=1 https://github.com/Teremok/nodejs-typescript-expressjs-inversify-ioc-graphql-starter.git <project_name>
- Install dependencies
cd <project_name>
yarn install
- Build and run the project
yarn start
Navigate to http://localhost:3000
The main purpose of this repository is to show a good end-to-end project setup and workflow for writing Node code in TypeScript. I will try to keep this as up-to-date as possible, but community contributions and recommendations for improvements are encourage and will be most welcome.
In the next few sections I will call out everything that changes when adding TypeScript to an Express project. Note that all of this has already been setup for this project, but feel free to use this as a reference for converting other Node.js project to TypeScript.
Note on editors! - TypeScript has great support in every editor.
TypeScript itself is simple to add to any project with yarn
.
yarn add typescript --dev
The most obvious difference in a TypeScript + Node project is the folder structure.
In a TypeScript project, you it's best to have separate source and distributable files.
TypeScript (.ts
) files live in your src
folder and after compilation are output as JavaScript (.js
) in the dist
folder.
The test
and views
folders remain top level as expected.
The full folder structure of this app is explained below:
Note! Make sure you have already built the app using
npm run build
oryarn run build
Name | Description |
---|---|
dist | Contains the distributable (or output) from your TypeScript build. This is the code you ship |
node_modules | Contains all your npm dependencies |
src | Contains your source code that will be compiled to the dist dir |
src/config | Project config code. Currently stores Inversify configuration. |
src/controllers | Controllers define functions that respond to various http requests |
src/models | Models define Mongoose schemas that will be used in storing and retrieving data from MongoDB |
src/public | Static assets that will be used client side |
src/types | Holds .d.ts files not found on DefinitelyTyped. Covered more in this section |
src/app.ts | Configured ExpressJs application |
src/server.ts | Entry point to your express app |
test | Contains your tests. Seperate from source because there is a different build process. |
views | Views define how your app renders on the client. In this case we're using pug |
.dockerignore | Docker ignore file |
.env.* | API keys, tokens, passwords, database URI. Clone this, but don't check it in to public repos. |
.graphqlconfig.yaml | GraphQL configuration |
.travis.yml | Used to configure Travis CI build |
copyStaticAssets.ts | Build script that copies images, fonts, and JS libs to the dist folder |
docker-compose.yml | Docker compose file |
package.json | File that contains npm dependencies as well as build scripts |
tsconfig.json | Config settings for compiling server code written in TypeScript |
tsconfig.tests.json | Config settings for compiling tests written in TypeScript |
tslint.json | Config settings for TSLint code style checking |
yarn.lock | Contains same dependency version info as package.json, but used with yarn |
It is rare for JavaScript projects not to have some kind of build pipeline these days, however Node projects typically have the least amount build configuration. Because of this I've tried to keep the build as simple as possible. If you're concerned about compile time, the main watch task takes ~2s to refresh.
TypeScript uses the file tsconfig.json
to adjust project compile options.
Let's dissect this project's tsconfig.json
, starting with the compilerOptions
which details how your project is compiled.
compilerOptions |
Description |
---|---|
"target": "es6" |
The output language level. Node supports ES6, so we can target that here |
"module": "commonjs" |
The output module type (in your .js files). Node uses commonjs, so that is what we use |
"sourceMap": true |
We want source maps to be output along side our JavaScript. See the debugging section |
"outDir": "dist" |
Location to output .js files after compilation |
"noImplicitAny": true |
Enables a stricter setting which throws errors when something has a default any value |
"moduleResolution": "node" |
TypeScript attempts to mimic Node's module resolution strategy. Read more here |
"baseUrl": "." |
Part of configuring module resolution. See path mapping section |
paths: {...} |
Part of configuring module resolution. See path mapping section |
The rest of the file define the TypeScript project context.
The project context is basically a set of options that determine which files are compiled when the compiler is invoked with a specific tsconfig.json
.
In this case, we use the following to define our project context:
"include": [
"src/**/*"
]
include
takes an array of glob patterns of files to include in the compilation.
This project is fairly simple and all of our .ts files are under the src
folder.
For more complex setups, you can include an exclude
array of glob patterns that removes specific files from the set defined with include
.
There is also a files
option which takes an array of individual file names which overrides both include
and exclude
.
All the different build steps are orchestrated via yarn scripts.
yarn scripts basically allow us to call (and chain) terminal commands via yarn.
This is nice because most JavaScript tools have easy to use command line utilities allowing us to not need grunt or gulp to manage our builds.
If you open package.json
, you will see a scripts
section with all the different scripts you can call.
To call a script, simply run yarn run <script-name>
from the command line.
You'll notice that yarn scripts can call each other which makes it easy to compose complex builds out of simple individual build scripts.
Below is a list of all the scripts this template has available:
yarn Script | Description |
---|---|
start |
Runs full build before starting all watch tasks. Can be invoked with yarn start |
debug |
Debugs full build before starting all watch tasks. |
serve |
Runs node on dist/server.js which is the apps entry point |
build |
Full build. Runs ALL build tasks (build:sass , build:ts , tslint , copy-static-assets ) |
build:sass |
Compiles all .scss files to .css files |
build:ts |
Compiles all source .ts files to .js files in the dist folder |
tslint |
Runs TSLint on project files |
copy-static-assets |
Calls script that copies JS libs, fonts, and images to dist directory |
watch |
Runs all watch tasks (TypeScript, Sass, Node). Use this if you're not touching static assets. |
watch:sass |
Same as build:sass but continuously watches .scss files and re-compiles when needed |
watch:ts |
Same as build:ts but continuously watches .ts files and re-compiles when needed |
watch:node |
Continuously monitors dist/serve.js |
watch:debug |
Same as watch but continuously watches all files and re-compiles when needed |
test |
Runs tests using Jest test runner |
TypeScript uses .d.ts
files to provide types for JavaScript libraries that were not written in TypeScript.
This is great because once you have a .d.ts
file, TypeScript can type check that library and provide you better help in your editor.
The TypeScript community actively shares all of the most up-to-date .d.ts
files for popular libraries on a GitHub repository called DefinitelyTyped.
Making sure that your .d.ts
files are setup correctly is super important because once they're in place, you get an incredible amount high quality of type checking (and thus bug catching, IntelliSense, and other editor tools) for free.
Note! Because we're using
"noImplicitAny": true
, we are required to have a.d.ts
file for every library we use. While you could setnoImplicitAny
tofalse
to silence errors about missing.d.ts
files, it is a best practice to have a.d.ts
file for every library. (Even the.d.ts
file is basically empty!)
For the most part, you'll find .d.ts
files for the libraries you are using on DefinitelyTyped.
These .d.ts
files can be easily installed into your project by using the npm scope @types
.
For example, if we want the .d.ts
file for jQuery, we can do so with yarn add @types/jquery --dev
.
Note! Be sure to add
--dev
to youryarn add
..d.ts
files are project dependencies, but only used at compile time and thus should be dev dependencies.
In this template, all the .d.ts
files have already been added to devDependencies
in package.json
, so you will get everything you need after running your first yarn install
.
Once .d.ts
files have been installed using npm, you should see them in your node_modules/@types
folder.
The compiler will always look in this folder for .d.ts
files when resolving JavaScript libraries.
If you try to install a .d.ts
file from @types
and it isn't found, or you check DefinitelyTyped and cannot find a specific library, you will want to create your own .d.ts file
.
In the src
folder of this project, you'll find the types
folder which holds the .d.ts
files that aren't on DefinitelyTyped (or weren't as of the time of this writing).
The compiler knows to look in node_modules/@types
by default, but to help the compiler find our own .d.ts
files we have to configure path mapping in our tsconfig.json
.
Path mapping can get pretty confusing, but the basic idea is that the TypeScript compiler will look in specific places, in a specific order when resolving modules, and we have the ability to tell the compiler exactly how to do it.
In the tsconfig.json
for this project you'll see the following:
"baseUrl": ".",
"paths": {
"*": [
"src/types/*"
]
}
This tells the TypeScript compiler that in addition to looking in node_modules/@types
for every import (*
) also look in our own .d.ts
file location <baseUrl>
+ src/types/*
.
So when we write something like:
import * as lusca from "lusca";
First the compiler will look for a d.ts
file in node_modules/@types
and then when it doesn't find one look in src/types
and find our file lusca.d.ts
.
Unless you are familiar with .d.ts
files, I strongly recommend trying to use the tool dts-gen first.
The README does a great job explaining how to use the tool, and for most cases, you'll get an excellent scaffold of a .d.ts
file to start with.
If you just want to silence the compiler for the time being, create a file called <some-library>.d.ts
in your types
folder and then add this line of code:
declare module "<some-library>";
If you want to invest some time into making a great .d.ts
file that will give you great type checking and IntelliSense, the TypeScript website has great docs on authoring .d.ts
files.
The reason it's so easy to get great .d.ts
files for most libraries is that developers like you contribute their work back to DefinitelyTyped.
Contributing .d.ts
files is a great way to get into the open source community if it's something you've never tried before, and as soon as your changes are accepted, every other developer in the world has access to your work.
If you're interested in giving it a shot, check out the guidance on DefinitelyTyped.
In general if you stick to the following steps you should have minimal .d.ts
issues;
- After installing any npm package as a dependency or dev dependency, immediately try to install the
.d.ts
file via@types
. - If the library has a
.d.ts
file on DefinitelyTyped, the install will succeed and you are done. If the install fails because the package doesn't exist, continue to step 3. - Make sure you project is configured for supplying your own
d.ts
files - Try to generate a
.d.ts
file with dts-gen. If it succeeds, you are done. If not, continue to step 5. - Create a file called
<some-library>.d.ts
in yourtypes
folder. - Add the following code:
declare module "<some-library>";
- At this point everything should compile with no errors and you can either improve the types in the
.d.ts
file by following this guide on authoring.d.ts
files or continue with no types. - If you are still having issues, let me know by sending me an email or pinging me on twitter, I will help you.
Debugging TypeScript is exactly like debugging JavaScript with one caveat, you need source maps.
Source maps allow you to drop break points in your TypeScript source code and have that break point be hit by the JavaScript that is being executed at runtime.
Note! - Source maps aren't specific to TypeScript. Anytime JavaScript is transformed (transpiled, compiled, optimized, minified, etc) you need source maps so that the code that is executed at runtime can be mapped back to the source that generated it.
The best part of source maps is when configured correctly, you don't even know they exist! So let's take a look at how we do that in this project.
First you need to make sure your tsconfig.json
has source map generation enabled:
"compilerOptions" {
"sourceMaps": true
}
With this option enabled, next to every .js
file that the TypeScript compiler outputs there will be a .map.js
file as well.
This .map.js
file provides the information necessary to map back to the source .ts
file while debugging.
Note! - It is also possible to generate "inline" source maps using
"inlineSourceMap": true
. This is more common when writing client side code because some bundlers need inline source maps to preserve the mapping through the bundle. Because we are writing Node.js code, we don't have to worry about this.
TODO rewrite to jasmine.
For this project, I chose Jest as our test framework. While Mocha is probably more common, Mocha seems to be looking for a new maintainer and setting up TypeScript testing in Jest is wicked simple.
To add TypeScript + Jest support, first install a few npm packages:
npm install -D jest ts-jest
jest
is the testing framework itself, and ts-jest
is just a simple function to make running TypeScript tests a little easier.
Jest's configuration lives in package.json
, so let's open it up and add the following code:
"jest": {
"globals": {
"__TS_CONFIG__": "tsconfig.json"
},
"moduleFileExtensions": [
"ts",
"js"
],
"transform": {
"^.+\\.(ts)$": "./node_modules/ts-jest/preprocessor.js"
},
"testMatch": [
"**/test/**/*.test.(ts|js)"
],
"testEnvironment": "node"
},
Basically we are telling Jest that we want it to consume all files that match the pattern "**/test/**/*.test.(ts|js)"
(all .test.ts
/.test.js
files in the test
folder), but we want to preprocess the .ts
files first.
This preprocess step is very flexible, but in our case, we just want to compile our TypeScript to JavaScript using our tsconfig.json
.
This all happens in memory when you run the tests, so there are no output .js
test files for you to manage.
Writing tests for web apps has entire books dedicated to it and best practices are strongly influenced by personal style, so I'm deliberately avoiding discussing how or when to write tests in this guide. However, if prescriptive guidance on testing is something that you're interested in, let me know, I'll do some homework and get back to you.
TSLint is a code linter which mainly helps catch minor code quality and style issues. TSLint is very similar to ESLint or JSLint but is built with TypeScript in mind.
Like most linters, TSLint has a wide set of configurable rules as well as support for custom rule sets.
All rules are configured through tslint.json
.
In this project, we are using a fairly basic set of rules with no additional custom rules.
The settings are largely based off the TSLint settings that we use to develop TypeScript itself.
Like the rest of our build steps, we use npm scripts to invoke TSLint. To run TSLint you can call the main build script or just the TSLint task.
yarn run build // runs full build including TSLint
yarn run tslint // runs only TSLint
Notice that TSLint is not a part of the main watch task. It can be annoying for TSLint to clutter the output window while in the middle of writing a function, so I elected to only run it only during the full build.
Dependencies are managed through package.json
.
In that file you'll find two sections:
Package | Description |
---|---|
async | Utility library that provides asynchronous control flow. |
bcrypt-nodejs | Library for hashing and salting user passwords. |
body-parser | Express 4 middleware. |
chalk | |
compression | Express 4 middleware. |
connect-mongo | MongoDB session store for Express. |
dotenv | Loads environment variables from .env file. |
errorhandler | Express 4 middleware. |
express | Node.js web framework. |
express-flash | Provides flash messages for Express. |
express-session | Express 4 middleware. |
express-status-monitor | |
express-validator | Easy form validation for Express. |
fbgraph | Facebook Graph API library. |
graphql | |
graphql-server-express | |
graphql-tools | |
inversify | |
lusca | CSRF middleware. |
mongoose | MongoDB ODM. |
morgan | Express 4 middleware. |
multer | |
nodemailer | Node.js library for sending emails. |
node-sass-middleware | |
passport | Simple and elegant authentication library for node.js |
passport-facebook | Sign-in with Facebook plugin. |
passport-local | Sign-in with Username and Password plugin. |
pug (jade) | Template engine for Express. |
reflect-metadata | |
request | Simplified HTTP request library. |
validator |
Package | Description |
---|---|
@types/* | |
concurrently | Utility that manages multiple concurrent tasks. Used with npm scripts |
jest | Reports real-time server metrics for Express. |
node-sass | GitHub API library. |
nodemon | |
shelljs | |
supertest | HTTP assertion library. |
trash-cli | |
ts-node | |
ts-test | Instagram API library. |
tslint | Linter (similar to ESLint) for TypeScript files |
typescript | JavaScript compiler/type checker that boosts JavaScript productivity |
To install or update these dependencies you can use yarn
.
Here is a section of miscellaneous tips.
A majority of this quick start's content was inspired or adapted from:
- Sahat's excellent Hackathon Starter project.
- Microsoft Node Starter project.