{"id":13398855,"url":"https://github.com/Microsoft/TypeScript-Node-Starter","last_synced_at":"2025-03-14T03:30:35.034Z","repository":{"id":37412414,"uuid":"90786190","full_name":"microsoft/TypeScript-Node-Starter","owner":"microsoft","description":"A reference example for TypeScript and Node with a detailed README describing how to use the two together.","archived":true,"fork":false,"pushed_at":"2022-06-24T15:40:58.000Z","size":1751,"stargazers_count":11272,"open_issues_count":69,"forks_count":2767,"subscribers_count":204,"default_branch":"master","last_synced_at":"2024-05-20T19:07:19.420Z","etag":null,"topics":["express","javascript","node","tslint","typescript"],"latest_commit_sha":null,"homepage":"","language":"SCSS","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/microsoft.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-05-09T19:53:52.000Z","updated_at":"2024-05-18T20:41:29.000Z","dependencies_parsed_at":"2022-07-18T13:17:10.322Z","dependency_job_id":null,"html_url":"https://github.com/microsoft/TypeScript-Node-Starter","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FTypeScript-Node-Starter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FTypeScript-Node-Starter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FTypeScript-Node-Starter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FTypeScript-Node-Starter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/microsoft","download_url":"https://codeload.github.com/microsoft/TypeScript-Node-Starter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":213240353,"owners_count":15557463,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["express","javascript","node","tslint","typescript"],"created_at":"2024-07-30T19:00:32.232Z","updated_at":"2024-07-30T19:03:08.723Z","avatar_url":"https://github.com/microsoft.png","language":"SCSS","readme":"# TypeScript Node Starter\n\nThe main purpose of this repository is to show a working Node.js API Server + front-end project and workflow for writing Node code in TypeScript.\n\nIt is not a goal to be a comprehensive and definitive guide to making a TypeScript and Node project, but as a working reference maintained by the community. If you are interested in starting a new TypeScript project - check out the bootstrapping tools reference in [the TypeScript Website](https://www.typescriptlang.org/docs/home.html)\n\n\n[![Dependency Status](https://david-dm.org/Microsoft/TypeScript-Node-Starter.svg)](https://david-dm.org/Microsoft/TypeScript-Node-Starter) [![Build Status](https://travis-ci.org/Microsoft/TypeScript-Node-Starter.svg?branch=master)](https://travis-ci.org/Microsoft/TypeScript-Node-Starter)\n\n![image](https://user-images.githubusercontent.com/820883/36764267-abbdb7f8-1be0-11e8-9678-2a9ea448d7f8.png)\n\n\n# Table of contents:\n\n- [Pre-reqs](#pre-reqs)\n- [Getting started](#getting-started)\n- [Deploying the app](#deploying-the-app)\n\t- [Pre-reqs](#Prerequisites)\n\t- [Deploying to Azure App Service](#deploying-to-azure-app-service)\n- [TypeScript + Node](#typescript--node)\n\t- [Getting TypeScript](#getting-typescript)\n\t- [Project Structure](#project-structure)\n\t- [Building the project](#building-the-project)\n\t- [Type Definition (`.d.ts`) Files](#type-definition-dts-files)\n\t- [Debugging](#debugging)\n\t- [Testing](#testing)\n\t- [ESLint](#eslint)\n- [Dependencies](#dependencies)\n\t- [`dependencies`](#dependencies)\n\t- [`devDependencies`](#devdependencies)\n- [Hackathon Starter Project](#hackathon-starter-project)\n\n# Pre-reqs\nTo build and run this app locally you will need a few things:\n- Install [Node.js](https://nodejs.org/en/)\n- Install [MongoDB](https://docs.mongodb.com/manual/installation/)\n- Install [VS Code](https://code.visualstudio.com/)\n\n# Getting started\n- Clone the repository\n```\ngit clone --depth=1 https://github.com/Microsoft/TypeScript-Node-Starter.git \u003cproject_name\u003e\n```\n- Install dependencies\n```\ncd \u003cproject_name\u003e\nnpm install\n```\n- Configure your mongoDB server\n```bash\n# create the db directory\nsudo mkdir -p /data/db\n# give the db correct read/write permissions\nsudo chmod 777 /data/db\n\n# starting from macOS 10.15 even the admin cannot create directory at root\n# so lets create the db directory under the home directory.\nmkdir -p ~/data/db\n# user account has automatically read and write permissions for ~/data/db.\n```\n- Start your mongoDB server (you'll probably want another command prompt)\n```bash\nmongod\n\n# on macOS 10.15 or above the db directory is under home directory\nmongod --dbpath ~/data/db\n```\n- Build and run the project\n```\nnpm run build\nnpm start\n```\nOr, if you're using VS Code, you can use `cmd + shift + b` to run the default build task (which is mapped to `npm run build`), and then you can use the command palette (`cmd + shift + p`) and select `Tasks: Run Task` \u003e `npm: start` to run `npm start` for you.\n\n\u003e **Note on editors!** - TypeScript has great support in [every editor](http://www.typescriptlang.org/index.html#download-links), but this project has been pre-configured for use with [VS Code](https://code.visualstudio.com/).\nThroughout the README We will try to call out specific places where VS Code really shines or where this project has been set up to take advantage of specific features.\n\nFinally, navigate to `http://localhost:3000` and you should see the template being served and rendered locally!\n\n# Deploying the app\nThere are many ways to deploy a Node app, and in general, nothing about the deployment process changes because you're using TypeScript.\nIn this section, I'll walk you through how to deploy this app to Azure App Service using the extensions available in VS Code because I think it is the easiest and fastest way to get started, as well as the most friendly workflow from a developer's perspective.\n\n## Prerequisites\n- [**Azure account**](https://azure.microsoft.com/en-us/free/) - If you don't have one, you can sign up for free.\nThe Azure free tier gives you plenty of resources to play around with including up to 10 App Service instances, which is what we will be using.\n- [**VS Code**](https://code.visualstudio.com/) - We'll be using the interface provided by VS Code to quickly deploy our app.\n- [**Azure App Service VS Code extension**](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureappservice) - In VS Code, search for `Azure App Service` in the extension marketplace (5th button down on the far left menu bar), install the extension, and then reload VS Code.\n- **Create a cloud database** -\nFor local development, running MongoDB on localhost is fine, however once we deploy we need a database with high availability.\nThe easiest way to achieve this is by using a managed cloud database.\nThere are many different providers, but the easiest one to get started with is [MongoDB Atlas](#create-a-managed-mongodb-with-atlas).\n- **SendGrid Account** -\nIf you don't have one, you can sign up for free, we will need it to send emails. There are many different providers that Nodemailer supports ([Well-known services](https://nodemailer.com/smtp/well-known/)), we'll be using [SendGrid](#sendgrid-account).\n\n### Create a managed MongoDB with Atlas\n1. Navigate to [MongoDB's website](https://www.mongodb.com/cloud/atlas), sign up for a free account, and then log in.\n2. After creating the account, enter the organization name, project name, and select your preferred language (JavaScript).\n3. Select the **Shared Cluster** to get a free version with up to 512 MB storage which is great for development purposes.\n4. On the \"Create a Starter Cluster\" page you can select cloud provider, region, region, cluster tier, and\nMongoDB settings, like version and backup frequency (Note: there is no option to create backups in the free tier).\n5. If you already know to which cloud provider and region you want to deploy later, you should select the same here for best performance. Otherwise select a region close to the location where you plan to deploy the application later.\n6. Select **M0 Sandbox** as the Cluster Tier, give your cluster a name, and then click the \"Create Cluster\" button.\n7. It will now take a couple of minutes to create the cluster and you will be redirected to the MongoDB Atlas Admin interface.\n8. Now you must configure access and security before you can use the database.\n9. To whitelist an IP address, go to the **Network Access** section and click the \"Add IP Address\" button. For local development you can select your current IP address.\n10. Create a user by selecting the **Add New Database User** in Database Access, adding a username and password (Password Authentication method) and give him read and write access to any database within the cluster.\nA user account is required to connect to the database, so remember these values because you will need them as part of your connection string.\n11. Within the Clusters section, click the **Connect** button in your cluster to connect to the database.\n12. You could now connect to the cluster using [MongoDB Compass](https://www.mongodb.com/products/compass), which is a graphical interface (GUI) to interact with the database.\n13. But we need to select **Connect your application** to get the connection string, it should look like this: `mongodb+srv://\u003cusername\u003e:\u003cpassword\u003e@your-cluster.12abc.mongodb.net/your-database?retryWrites=true\u0026w=majority`\nand replace `\u003cusername\u003e` and `\u003cpassword\u003e` with the credentials you just created.\nBack in your project, open your `.env` file and update `MONGODB_URI` with your new connection string.\n    \u003e NOTE! - If you don't have an `.env` file yet, rename `.env.example` to `.env` and follow the comments to update the values in that file.\n14. **Success!**\nYou can test that it works locally by updating `MONGODB_URI_LOCAL` to the same connection string you just updated in `MONGO_URI`.\nAfter rebuilding/serving, the app should work, but users that were previously created in local testing will not exist in the new database!\nDon't forget to return the `MONGO_URI_LOCAL` to your local test database (if you so desire).\n\nYou can find **more information** about how to get started with Atlas [here](https://docs.atlas.mongodb.com/getting-started/).\n\n### SendGrid Account\n1. Navigate to [SendGrid's Website](https://sendgrid.com/), sign up for a free account, and complete the verification process.\n2. Open your `.env` file and update `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` with your SendGrid username and password respectively.\n\n## Deploying to Azure App Service\nDeploying from VS Code can be broken into the following steps:\n1. Authenticate your Azure account in VS Code\n2. Build your app\n3. Zip deploy using the Azure App Service extension\n\n### Sign in to your Azure account\n1. Open VS Code\n2. Expand the Azure App Service menu in the explorer menu\n    - If you don't see this, you might not have the `Azure App Service` extension installed.\n    See the pre-reqs section.\n3. Click `Sign in to Azure...`\n4. Choose `Copy \u0026 Open` from the resulting dialog\n    - This will open `aka.ms/devicelogin` in a browser window.\n    If it doesn't, just navigate there manually.\n5. Paste in the code that is on your clipboard.\n6. Go back to VS Code, you should now be signed in.\nYou can confirm that everything worked by seeing your Azure subscription listed in the Azure App Service section of the explorer window.\nAdditionally, you should see the email associated with your account listed in the status bar at the bottom of VS Code.\n\n### Build the app\nBuilding the app locally is required to generate a zip to deploy because the App Service won't execute build tasks.\nBuild the app however you normally would:\n- `ctrl + shift + b` - kicks off default build in VS Code\n- execute `npm run build` from a terminal window\n\n### Zip deploy from VS Code\n1. Make sure your app is built, whatever is currently in your `dist` and `node_modules` folders will be the app that is deployed.\n2. Click the blue up arrow (Deploy to Web App) on the Azure App Service section of the explorer window.\n3. Choose the entire project directory.\nIf you haven't changed the name, this will be `TypeScript-Node-Starter`.\n4. Choose the subscription you want this app to be billed to (don't worry, it will be free).\n5. Choose `Create New Web App`\n6. Enter a globally unique name -\nThis will be part of the URL that azure generates, so it has to be unique, but if you're planning on adding a custom domain later, it's not that important. I usually just add random numbers to the end of the app name, ie. typescript-node-starter-15121214.\n7. Choose a resource group -\nIf you don't know what this is, just create a new one.\nIf you have lots of cloud resources that should be logically grouped together (think an app service, and a database that supports that app) then you would want to put them in the same resource group.\nThis can always be updated later though.\nIf you create a new resource group, you'll also be prompted to pick a location for that group.\nPick something geographically close to where your users are.\n8. Choose `Create new App Service Plan` -\nAn app service plan mainly is what determines the size and cost of the hardware your app will run on, but it also manages some other settings which we can ignore for now.\n9. Choose `B1 - Basic` - This one is free.\nIf you know what you're doing, feel free to select a stronger pricing tier.\n10. Choose your target node runtime version - We are deploying to Linux machines, and in addition we can choose the exact node runtime we want.\nIf you don't know what you want, choose whatever the current LTS build is.\n11. Grab a cup of coffee - You'll see everything you just selected getting created in the output window.\nAll of this is powered by the [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/overview?view=azure-cli-latest) and can be easily replicated if you decide you want to customize this process.\nThis deployment is not the fastest option (but it is the easiest!). We are literally bundling everything in your project (including the massive node_modules folder) and uploading it to our Azure app service. Times will vary, but as a baseline, my deployment took roughly 6 minutes.\n12. Add `NODE_ENV` environment variable - In the App Service section of the explorer window, expand the newly created service, right click on **Application Settings**, select **Add New Settings...**, and add `NODE_ENV` as the key and `production` as the value.\nThis setting determines which database to point to.\nIf you haven't created a cloud database yet, see [the setup instructions](#Create a managed MongoDB with MongoLab).\n13. Profit!\n\n### Troubleshooting failed deployments\nDeployment can fail for various reasons, if you get stuck with a page that says *Service Unavailable* or some other error, [open an issue](https://github.com/Microsoft/TypeScript-Node-Starter/issues/new) and I'll try to help you resolve the problems.\n\n# TypeScript + Node\nIn the next few sections I will call out everything that changes when adding TypeScript to an Express project.\nNote that all of this has already been set up for this project, but feel free to use this as a reference for converting other Node.js projects to TypeScript.\n\n## Getting TypeScript\nTypeScript itself is simple to add to any project with `npm`.\n```\nnpm install -D typescript\n```\nIf you're using VS Code then you're good to go!\nVS Code will detect and use the TypeScript version you have installed in your `node_modules` folder.\nFor other editors, make sure you have the corresponding [TypeScript plugin](http://www.typescriptlang.org/index.html#download-links).\n\n## Project Structure\nThe most obvious difference in a TypeScript + Node project is the folder structure.\nIn a TypeScript project, it's best to have separate _source_  and _distributable_ files.\nTypeScript (`.ts`) files live in your `src` folder and after compilation are output as JavaScript (`.js`) in the `dist` folder.\nThe `test` and `views` folders remain top level as expected.\n\nThe full folder structure of this app is explained below:\n\n\u003e **Note!** Make sure you have already built the app using `npm run build`\n\n| Name | Description |\n| ------------------------ | --------------------------------------------------------------------------------------------- |\n| **.vscode**              | Contains VS Code specific settings                                                            |\n| **.github**              | Contains GitHub settings and configurations, including the GitHub Actions workflows            |\n| **dist**                 | Contains the distributable (or output) from your TypeScript build. This is the code you ship  |\n| **node_modules**         | Contains all your npm dependencies                                                            |\n| **src**                  | Contains your source code that will be compiled to the dist dir                               |\n| **src/config**           | Passport authentication strategies and login middleware. Add other complex config code here   |\n| **src/controllers**      | Controllers define functions that respond to various http requests                            |\n| **src/models**           | Models define Mongoose schemas that will be used in storing and retrieving data from MongoDB  |\n| **src/public**           | Static assets that will be used client side                                                   |\n| **src/types**            | Holds .d.ts files not found on DefinitelyTyped. Covered more in this [section](#type-definition-dts-files)          |\n| **src**/server.ts        | Entry point to your express app                                                               |\n| **test**                 | Contains your tests. Separate from source because there is a different build process.         |\n| **views**                | Views define how your app renders on the client. In this case we're using pug                 |\n| .env.example             | API keys, tokens, passwords, database URI. Clone this, but don't check it in to public repos. |\n| .travis.yml              | Used to configure Travis CI build                                                             |\n| .copyStaticAssets.ts     | Build script that copies images, fonts, and JS libs to the dist folder                        |\n| jest.config.js           | Used to configure Jest running tests written in TypeScript                                    |\n| package.json             | File that contains npm dependencies as well as [build scripts](#what-if-a-library-isnt-on-definitelytyped)                          |\n| tsconfig.json            | Config settings for compiling server code written in TypeScript                               |\n| tsconfig.tests.json      | Config settings for compiling tests written in TypeScript                                     |\n| .eslintrc                | Config settings for ESLint code style checking                                                |\n| .eslintignore            | Config settings for paths to exclude from linting                                             |\n\n## Building the project\nIt is rare for JavaScript projects not to have some kind of build pipeline these days, however Node projects typically have the least amount of build configuration.\nBecause of this I've tried to keep the build as simple as possible.\nIf you're concerned about compile time, the main watch task takes ~2s to refresh.\n\n### Configuring TypeScript compilation\nTypeScript uses the file `tsconfig.json` to adjust project compile options.\nLet's dissect this project's `tsconfig.json`, starting with the `compilerOptions` which details how your project is compiled.\n```json\n\"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"esModuleInterop\": true,\n    \"target\": \"es6\",\n    \"noImplicitAny\": true,\n    \"moduleResolution\": \"node\",\n    \"sourceMap\": true,\n    \"outDir\": \"dist\",\n    \"baseUrl\": \".\",\n    \"paths\": {\n        \"*\": [\n            \"node_modules/*\",\n            \"src/types/*\"\n        ]\n    }\n},\n```\n\n| `compilerOptions` | Description |\n| ---------------------------------- | ------------------------------------------------------------------------------------------------------ |\n| `\"module\": \"commonjs\"`             | The **output** module type (in your `.js` files). Node uses commonjs, so that is what we use            |\n| `\"esModuleInterop\": true,`         | Allows usage of an alternate module import syntax: `import foo from 'foo';`                            |\n| `\"target\": \"es6\"`                  | The output language level. Node supports ES6, so we can target that here                               |\n| `\"noImplicitAny\": true`            | Enables a stricter setting which throws errors when something has a default `any` value                |\n| `\"moduleResolution\": \"node\"`       | TypeScript attempts to mimic Node's module resolution strategy. Read more [here](https://www.typescriptlang.org/docs/handbook/module-resolution.html#node)                                                                    |\n| `\"sourceMap\": true`                | We want source maps to be output along side our JavaScript. See the [debugging](#debugging) section    |\n| `\"outDir\": \"dist\"`                 | Location to output `.js` files after compilation                                                        |\n| `\"baseUrl\": \".\"`                   | Part of configuring module resolution. See [path mapping section](#installing-dts-files-from-definitelytyped) |\n| `paths: {...}`                     | Part of configuring module resolution. See [path mapping section](#installing-dts-files-from-definitelytyped) |\n\nThe rest of the file define the TypeScript project context.\nThe project context is basically a set of options that determine which files are compiled when the compiler is invoked with a specific `tsconfig.json`.\nIn this case, we use the following to define our project context:\n```json\n\"include\": [\n    \"src/**/*\"\n]\n```\n`include` takes an array of glob patterns of files to include in the compilation.\nThis project is fairly simple and all of our .ts files are under the `src` folder.\nFor more complex setups, you can include an `exclude` array of glob patterns that removes specific files from the set defined with `include`.\nThere is also a `files` option which takes an array of individual file names which overrides both `include` and `exclude`.\n\n\n### Running the build\nAll the different build steps are orchestrated via [npm scripts](https://docs.npmjs.com/misc/scripts).\nNpm scripts basically allow us to call (and chain) terminal commands via npm.\nThis 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.\nIf you open `package.json`, you will see a `scripts` section with all the different scripts you can call.\nTo call a script, simply run `npm run \u003cscript-name\u003e` from the command line.\nYou'll notice that npm scripts can call each other which makes it easy to compose complex builds out of simple individual build scripts.\nBelow is a list of all the scripts this template has available:\n\n\n| Npm Script | Description  |\n| ------------------------- | ------------------------------------------------------------------------------------------------- |\n| `build-sass`              | Compiles all `.scss` files to `.css` files                                                        |\n| `build-ts`                | Compiles all source `.ts` files to `.js` files in the `dist` folder                               |\n| `build`                   | Full build. Runs ALL build tasks (`build-sass`, `build-ts`, `lint`, `copy-static-assets`)         |\n| `copy-static-assets`      | Calls script that copies JS libs, fonts, and images to dist directory                             |\n| `debug`                   | Performs a full build and then serves the app in watch mode                                       |\n| `lint`                    | Runs ESLint on project files                                                                      |\n| `serve-debug`             | Runs the app with the --inspect flag                                                              |\n| `serve`                   | Runs node on `dist/server.js` which is the apps entry point                                       |\n| `start`                   | Does the same as 'npm run serve'. Can be invoked with `npm start`                                 |\n| `test`                    | Runs tests using Jest test runner                                                                 |\n| `watch-debug`             | The same as `watch` but includes the --inspect flag so you can attach a debugger                  |\n| `watch-node`              | Runs node with nodemon so the process restarts if it crashes. Used in the main watch task         |\n| `watch-sass`              | Same as `build-sass` but continuously watches `.scss` files and re-compiles when needed           |\n| `watch-test`              | Runs tests in watch mode                                                                          |\n| `watch-ts`                | Same as `build-ts` but continuously watches `.ts` files and re-compiles when needed               |\n| `watch`                   | Runs all watch tasks (TypeScript, Sass, Node). Use this if you're not touching static assets.     |\n\n## Type Definition (`.d.ts`) Files\nTypeScript uses `.d.ts` files to provide types for JavaScript libraries that were not written in TypeScript.\nThis is great because once you have a `.d.ts` file, TypeScript can type check that library and provide you better help in your editor.\nThe TypeScript community actively shares all the most up-to-date `.d.ts` files for popular libraries on a GitHub repository called [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types).\nMaking sure that your `.d.ts` files are setup correctly is super important because once they're in place, you get an incredible amount of high quality type checking (and thus bug catching, IntelliSense, and other editor tools) for free.\n\n\u003e **Note!** Because we're using `\"noImplicitAny\": true`, we are required to have a `.d.ts` file for **every** library we use. While you could set `noImplicitAny` to `false` to silence errors about missing `.d.ts` files, it is a best practice to have a `.d.ts` file for every library. (Even if the `.d.ts` file is [basically empty!](#writing-a-dts-file))\n\n### Installing `.d.ts` files from DefinitelyTyped\nFor the most part, you'll find `.d.ts` files for the libraries you are using on DefinitelyTyped.\nThese `.d.ts` files can be easily installed into your project by using the npm scope `@types`.\nFor example, if we want the `.d.ts` file for jQuery, we can do so with `npm install --save-dev @types/jquery`.\n\n\u003e **Note!** Be sure to add `--save-dev` (or `-D`) to your `npm install`. `.d.ts` files are project dependencies, but only used at compile time and thus should be dev dependencies.\n\nIn 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 `npm install`.\nOnce `.d.ts` files have been installed using npm, you should see them in your `node_modules/@types` folder.\nThe compiler will always look in this folder for `.d.ts` files when resolving JavaScript libraries.\n\n### What if a library isn't on DefinitelyTyped?\nIf 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`.\nIn 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).\n\n#### Setting up TypeScript to look for `.d.ts` files in another folder\nThe 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`.\nPath 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.\nIn the `tsconfig.json` for this project you'll see the following:\n```json\n\"baseUrl\": \".\",\n\"paths\": {\n    \"*\": [\n        \"node_modules/*\",\n        \"src/types/*\"\n    ]\n}\n```\nThis 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 `\u003cbaseUrl\u003e` + `src/types/*`.\nSo when we write something like:\n```ts\nimport * as flash from \"express-flash\";\n```\nFirst 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 `express-flash.d.ts`.\n\n#### Using `dts-gen`\nUnless you are familiar with `.d.ts` files, I strongly recommend trying to use the tool [dts-gen](https://github.com/Microsoft/dts-gen) first.\nThe [README](https://github.com/Microsoft/dts-gen#dts-gen-a-typescript-definition-file-generator) 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.\nIn this project, `bcrypt-nodejs.d.ts`, `fbgraph.d.ts`, and `lusca.d.ts` were all generated using `dts-gen`.\n\n#### Writing a `.d.ts` file\nIf generating a `.d.ts` using `dts-gen` isn't working, [you should tell me about it first](https://www.surveymonkey.com/r/LN2CV82), but then you can create your own `.d.ts` file.\n\nIf you just want to silence the compiler for the time being, create a file called `\u003csome-library\u003e.d.ts` in your `types` folder and then add this line of code:\n```ts\ndeclare module \"\u003csome-library\u003e\";\n```\nIf 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](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).\n\n#### Contributing to DefinitelyTyped\nThe 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.\nContributing `.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.\n\nIf you're interested in giving it a shot, check out the [guidance on DefinitelyTyped](https://github.com/definitelyTyped/DefinitelyTyped/#how-can-i-contribute).\nIf you're not interested, [you should tell me why](https://www.surveymonkey.com/r/LN2CV82) so we can help make it easier in the future!\n\n### Summary of `.d.ts` management\nIn general if you stick to the following steps you should have minimal `.d.ts` issues;\n1. After installing any npm package as a dependency or dev dependency, immediately try to install the `.d.ts` file via `@types`.\n2. If the library has a `.d.ts` file on DefinitelyTyped, the installation will succeed, and you are done.\nIf the install fails because the package doesn't exist, continue to step 3.\n3. Make sure you project is [configured for supplying your own `d.ts` files](#setting-up-typescript-to-look-for-dts-files-in-another-folder)\n4. Try to [generate a `.d.ts` file with dts-gen](#using-dts-gen).\nIf it succeeds, you are done.\nIf not, continue to step 5.\n5. Create a file called `\u003csome-library\u003e.d.ts` in your `types` folder.\n6. Add the following code:\n```ts\ndeclare module \"\u003csome-library\u003e\";\n```\n7. 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](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html) or continue with no types.\n8. If you are still having issues, let me know by emailing me or pinging me on twitter, I will help you.\n\n## Debugging\nDebugging TypeScript is exactly like debugging JavaScript with one caveat, you need source maps.\n\n### Source maps\nSource 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.\n\n\u003e **Note!** - Source maps aren't specific to TypeScript.\nAnytime 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.\n\nThe 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.\n\n#### Configuring source maps\nFirst you need to make sure your `tsconfig.json` has source map generation enabled:\n```json\n\"compilerOptions\" {\n    \"sourceMap\": true\n}\n```\nWith this option enabled, next to every `.js` file that the TypeScript compiler outputs there will be a `.map.js` file as well.\nThis `.map.js` file provides the information necessary to map back to the source `.ts` file while debugging.\n\n\u003e **Note!** - It is also possible to generate \"inline\" source maps using `\"inlineSourceMap\": true`.\nThis is more common when writing client side code because some bundlers need inline source maps to preserve the mapping through the bundle.\nBecause we are writing Node.js code, we don't have to worry about this.\n\n### Using the debugger in VS Code\nDebugging is one of the places where VS Code really shines over other editors.\nNode.js debugging in VS Code is easy to set up and even easier to use.\nThis project comes pre-configured with everything you need to get started.\n\nWhen you hit `F5` in VS Code, it looks for a top level `.vscode` folder with a `launch.json` file.\n\nYou can debug in the following ways:\n* **Launch Program** - transpile typescript to javascript via npm build, then launch the app with the debugger attached on startup\n* **Attach by Process ID** - run the project in debug mode. This is mostly identical to the \"Node.js: Attach by Process ID\" template with one minor change.\nWe added `\"protocol\": \"inspector\"` which tells VS Code that we're using the latest version of Node which uses a new debug protocol.\n* **Jest Current File** - have a Jest test file open and active in VSCode, then debug this specific file by setting break point. All tests are not run.\n* **Jest all** -  run all tests, set a break point.\n\nIn this file, you can tell VS Code exactly what you want to do:\n```json\n[\n        {\n            \"name\": \"Launch Program\",\n            \"type\": \"node\",\n            \"program\": \"${workspaceFolder}/dist/server.js\",\n            \"request\": \"launch\",\n            \"preLaunchTask\": \"npm: build\"\n        },\n        {\n            \"type\": \"node\",\n            \"request\": \"attach\",\n            \"name\": \"Attach by Process ID\",\n            \"processId\": \"${command:PickProcess}\",\n            \"protocol\": \"inspector\"\n        },\n        {\n            \"type\": \"node\",\n            \"request\": \"launch\",\n            \"name\": \"Jest Current File\",\n            \"program\": \"${workspaceFolder}/node_modules/.bin/jest\",\n            \"args\": [\n                \"${fileBasenameNoExtension}\",\n                \"--detectOpenHandles\"\n            ],\n            \"console\": \"integratedTerminal\",\n            \"internalConsoleOptions\": \"neverOpen\",\n            \"disableOptimisticBPs\": true,\n            \"windows\": {\n                \"program\": \"${workspaceFolder}/node_modules/jest/bin/jest\",\n            }\n        },\n        {\n            \"type\": \"node\",\n            \"request\": \"launch\",\n            \"name\": \"Jest all\",\n            \"runtimeExecutable\": \"npm\",\n            \"runtimeArgs\": [\n                \"run-script\",\n                \"test\"\n            ],\n            \"port\": 9229,\n            \"skipFiles\": [\n                \"\u003cnode_internals\u003e/**\"\n            ]\n        },\n    ]\n```\n\nWith this file in place, you can hit `F5` to attach a debugger.\nYou will probably have multiple node processes running, so you need to find the one that shows `node dist/server.js`.\nNow just set your breakpoints and go!\n\n## Testing\nFor this project, I chose [Jest](https://facebook.github.io/jest/) as our test framework.\nWhile Mocha is probably more common, Mocha seems to be looking for a new maintainer and setting up TypeScript testing in Jest is wicked simple.\n\n### Install the components\nTo add TypeScript + Jest support, first install a few npm packages:\n```\nnpm install -D jest ts-jest\n```\n`jest` is the testing framework itself, and `ts-jest` is just a simple function to make running TypeScript tests a little easier.\n\n### Configure Jest\nJest's configuration lives in `jest.config.js`, so let's open it up and add the following code:\n```js\nmodule.exports = {\n    globals: {\n        'ts-jest': {\n            tsconfigFile: 'tsconfig.json'\n        }\n    },\n    moduleFileExtensions: [\n        'ts',\n        'js'\n    ],\n    transform: {\n        '^.+\\\\.(ts|tsx)$': './node_modules/ts-jest/preprocessor.js'\n    },\n    testMatch: [\n        '**/test/**/*.test.(ts|js)'\n    ],\n    testEnvironment: 'node'\n};\n```\nBasically 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.\nThis preprocess step is very flexible, but in our case, we just want to compile our TypeScript to JavaScript using our `tsconfig.json`.\nThis all happens in memory when you run the tests, so there are no output `.js` test files for you to manage.\n\n### Running tests\nSimply run `npm run test`.\nNote this will also generate a coverage report.\n\n### Writing tests\nWriting 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.\nHowever, if prescriptive guidance on testing is something that you're interested in, [let me know](https://www.surveymonkey.com/r/LN2CV82), I'll do some homework and get back to you.\n\n## ESLint\nESLint is a code linter which mainly helps catch quickly minor code quality and style issues.\n\n### ESLint rules\nLike most linters, ESLint has a wide set of configurable rules as well as support for custom rule sets.\nAll rules are configured through `.eslintrc` configuration file.\nIn this project, we are using a fairly basic set of rules with no additional custom rules.\n\n### Running ESLint\nLike the rest of our build steps, we use npm scripts to invoke ESLint.\nTo run ESLint you can call the main build script or just the ESLint task.\n```\nnpm run build   // runs full build including ESLint\nnpm run lint    // runs only ESLint\n```\nNotice that ESLint is not a part of the main watch task.\n\nIf you are interested in seeing ESLint feedback as soon as possible, I strongly recommend the [VS Code ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint).\n\n### VSCode Extensions\n\nTo enhance your development experience while working in VSCode we also provide you a list of the suggested extensions for working with this project:\n\n![Suggested Extensions In VSCode](https://user-images.githubusercontent.com/14539/34583539-6f290a30-f198-11e7-8804-30f40d418e20.png)\n\n- [VS Code ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)\n- [Code Spell Checker](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker)\n- [Azure Cosmos DB](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-cosmosdb)\n- [Azure App Service](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureappservice)\n\n# Dependencies\nDependencies are managed through `package.json`.\nIn that file you'll find two sections:\n\n## `dependencies`\n\n| Package                         | Description                                                           |\n| ------------------------------- | --------------------------------------------------------------------- |\n| async                           | Utility library that provides asynchronous control flow.               |\n| bcrypt-nodejs                   | Library for hashing and salting user passwords.                       |\n| bluebird                        | Promise library                                                       |\n| body-parser                     | Express 4 middleware.                                                 |\n| compression                     | Express 4 middleware.                                                 |\n| connect-mongo                   | MongoDB session store for Express.                                    |\n| dotenv                          | Loads environment variables from .env file.                            |\n| errorhandler                    | Express 4 middleware.                                                 |\n| express                         | Node.js web framework.                                                |\n| express-flash                    | Provides flash messages for Express.                                   |\n| express-session                 | Express 4 middleware.                                                 |\n| express-validator               | Easy form validation for Express.                                     |\n| fbgraph                         | Facebook Graph API library.                                           |\n| lodash                          | General utility library.                                              |\n| lusca                           | CSRF middleware.                                                      |\n| mongoose                        | MongoDB ODM.                                                          |\n| nodemailer                      | Node.js library for sending emails.                                   |\n| passport                        | Simple and elegant authentication library for node.js                 |\n| passport-facebook               | Sign-in with Facebook plugin.                                         |\n| passport-local                  | Sign-in with Username and Password plugin.                            |\n| pug (jade)                      | Template engine for Express.                                          |\n| request                         | Simplified HTTP request library.                                       |\n| request-promise                 | Promisified HTTP request library. Let's us use async/await             |\n| winston                         | Logging library                                                       |\n\n## `devDependencies`\n\n| Package                         | Description                                                            |\n| ------------------------------- | ---------------------------------------------------------------------- |\n| @types                          | Dependencies in this folder are `.d.ts` files used to provide types    |\n| chai                            | Testing utility library that makes it easier to write tests            |\n| concurrently                    | Utility that manages multiple concurrent tasks. Used with npm scripts  |\n| jest                            | Testing library for JavaScript.                                        |\n| sass                            | Allows to compile .scss files to .css                                  |\n| nodemon                         | Utility that automatically restarts node process when it crashes       |\n| supertest                       | HTTP assertion library.                                                |\n| ts-jest                         | A preprocessor with sourcemap support to help use TypeScript with Jest.|\n| ts-node                         | Enables directly running TS files. Used to run `copy-static-assets.ts` |\n| eslint                          | Linter for JavaScript and TypeScript files                             |\n| typescript                      | JavaScript compiler/type checker that boosts JavaScript productivity   |\n\nTo install or update these dependencies you can use `npm install` or `npm update`.\n\n# Hackathon Starter Project\nA majority of this quick start's content was inspired or adapted from Sahat's excellent [Hackathon Starter project](https://github.com/sahat/hackathon-starter).\n\n## License\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the [MIT](LICENSE) License.\n","funding_links":[],"categories":["Node.js","TypeScript Starter/Boilerplate","GitHub","Typescript"],"sub_categories":["英文资源","Window"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMicrosoft%2FTypeScript-Node-Starter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FMicrosoft%2FTypeScript-Node-Starter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMicrosoft%2FTypeScript-Node-Starter/lists"}