Giter Site home page Giter Site logo

microsoft / typescript-node-starter Goto Github PK

View Code? Open in Web Editor NEW
11.3K 203.0 2.8K 1.71 MB

A reference example for TypeScript and Node with a detailed README describing how to use the two together.

License: MIT License

JavaScript 0.10% TypeScript 9.96% Shell 0.25% SCSS 85.13% Pug 4.56%
typescript node express javascript tslint

typescript-node-starter's Introduction

TypeScript Node Starter

The 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.

It 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

Dependency Status Build Status

image

Table of contents:

Pre-reqs

To build and run this app locally you will need a few things:

Getting started

  • Clone the repository
git clone --depth=1 https://github.com/Microsoft/TypeScript-Node-Starter.git <project_name>
  • Install dependencies
cd <project_name>
npm install
  • Configure your mongoDB server
# create the db directory
sudo mkdir -p /data/db
# give the db correct read/write permissions
sudo chmod 777 /data/db

# starting from macOS 10.15 even the admin cannot create directory at root
# so lets create the db directory under the home directory.
mkdir -p ~/data/db
# user account has automatically read and write permissions for ~/data/db.
  • Start your mongoDB server (you'll probably want another command prompt)
mongod

# on macOS 10.15 or above the db directory is under home directory
mongod --dbpath ~/data/db
  • Build and run the project
npm run build
npm start

Or, 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 > npm: start to run npm start for you.

Note on editors! - TypeScript has great support in every editor, but this project has been pre-configured for use with VS Code. Throughout 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.

Finally, navigate to http://localhost:3000 and you should see the template being served and rendered locally!

Deploying the app

There are many ways to deploy a Node app, and in general, nothing about the deployment process changes because you're using TypeScript. In 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.

Prerequisites

  • Azure account - If you don't have one, you can sign up for free. The 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.
  • VS Code - We'll be using the interface provided by VS Code to quickly deploy our app.
  • Azure App Service VS Code extension - 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.
  • Create a cloud database - For local development, running MongoDB on localhost is fine, however once we deploy we need a database with high availability. The easiest way to achieve this is by using a managed cloud database. There are many different providers, but the easiest one to get started with is MongoDB Atlas.
  • SendGrid Account - If 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), we'll be using SendGrid.

Create a managed MongoDB with Atlas

  1. Navigate to MongoDB's website, sign up for a free account, and then log in.
  2. After creating the account, enter the organization name, project name, and select your preferred language (JavaScript).
  3. Select the Shared Cluster to get a free version with up to 512 MB storage which is great for development purposes.
  4. On the "Create a Starter Cluster" page you can select cloud provider, region, region, cluster tier, and MongoDB settings, like version and backup frequency (Note: there is no option to create backups in the free tier).
  5. 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.
  6. Select M0 Sandbox as the Cluster Tier, give your cluster a name, and then click the "Create Cluster" button.
  7. It will now take a couple of minutes to create the cluster and you will be redirected to the MongoDB Atlas Admin interface.
  8. Now you must configure access and security before you can use the database.
  9. 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.
  10. 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. A user account is required to connect to the database, so remember these values because you will need them as part of your connection string.
  11. Within the Clusters section, click the Connect button in your cluster to connect to the database.
  12. You could now connect to the cluster using MongoDB Compass, which is a graphical interface (GUI) to interact with the database.
  13. But we need to select Connect your application to get the connection string, it should look like this: mongodb+srv://<username>:<password>@your-cluster.12abc.mongodb.net/your-database?retryWrites=true&w=majority and replace <username> and <password> with the credentials you just created. Back in your project, open your .env file and update MONGODB_URI with your new connection string.

    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.

  14. Success! You can test that it works locally by updating MONGODB_URI_LOCAL to the same connection string you just updated in MONGO_URI. After rebuilding/serving, the app should work, but users that were previously created in local testing will not exist in the new database! Don't forget to return the MONGO_URI_LOCAL to your local test database (if you so desire).

You can find more information about how to get started with Atlas here.

SendGrid Account

  1. Navigate to SendGrid's Website, sign up for a free account, and complete the verification process.
  2. Open your .env file and update SENDGRID_USERNAME and SENDGRID_PASSWORD with your SendGrid username and password respectively.

Deploying to Azure App Service

Deploying from VS Code can be broken into the following steps:

  1. Authenticate your Azure account in VS Code
  2. Build your app
  3. Zip deploy using the Azure App Service extension

Sign in to your Azure account

  1. Open VS Code
  2. Expand the Azure App Service menu in the explorer menu
    • If you don't see this, you might not have the Azure App Service extension installed. See the pre-reqs section.
  3. Click Sign in to Azure...
  4. Choose Copy & Open from the resulting dialog
    • This will open aka.ms/devicelogin in a browser window. If it doesn't, just navigate there manually.
  5. Paste in the code that is on your clipboard.
  6. Go back to VS Code, you should now be signed in. You can confirm that everything worked by seeing your Azure subscription listed in the Azure App Service section of the explorer window. Additionally, you should see the email associated with your account listed in the status bar at the bottom of VS Code.

Build the app

Building the app locally is required to generate a zip to deploy because the App Service won't execute build tasks. Build the app however you normally would:

  • ctrl + shift + b - kicks off default build in VS Code
  • execute npm run build from a terminal window

Zip deploy from VS Code

  1. Make sure your app is built, whatever is currently in your dist and node_modules folders will be the app that is deployed.
  2. Click the blue up arrow (Deploy to Web App) on the Azure App Service section of the explorer window.
  3. Choose the entire project directory. If you haven't changed the name, this will be TypeScript-Node-Starter.
  4. Choose the subscription you want this app to be billed to (don't worry, it will be free).
  5. Choose Create New Web App
  6. Enter a globally unique name - This 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.
  7. Choose a resource group - If you don't know what this is, just create a new one. If 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. This can always be updated later though. If you create a new resource group, you'll also be prompted to pick a location for that group. Pick something geographically close to where your users are.
  8. Choose Create new App Service Plan - An 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.
  9. Choose B1 - Basic - This one is free. If you know what you're doing, feel free to select a stronger pricing tier.
  10. Choose your target node runtime version - We are deploying to Linux machines, and in addition we can choose the exact node runtime we want. If you don't know what you want, choose whatever the current LTS build is.
  11. Grab a cup of coffee - You'll see everything you just selected getting created in the output window. All of this is powered by the Azure CLI and can be easily replicated if you decide you want to customize this process. This 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.
  12. 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. This setting determines which database to point to. If you haven't created a cloud database yet, see [the setup instructions](#Create a managed MongoDB with MongoLab).
  13. Profit!

Troubleshooting failed deployments

Deployment can fail for various reasons, if you get stuck with a page that says Service Unavailable or some other error, open an issue and I'll try to help you resolve the problems.

TypeScript + Node

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 set up for this project, but feel free to use this as a reference for converting other Node.js projects to TypeScript.

Getting TypeScript

TypeScript itself is simple to add to any project with npm.

npm install -D typescript

If you're using VS Code then you're good to go! VS Code will detect and use the TypeScript version you have installed in your node_modules folder. For other editors, make sure you have the corresponding TypeScript plugin.

Project Structure

The most obvious difference in a TypeScript + Node project is the folder structure. In a TypeScript project, 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

Name Description
.vscode Contains VS Code specific settings
.github Contains GitHub settings and configurations, including the GitHub Actions workflows
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 Passport authentication strategies and login middleware. Add other complex config code here
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/server.ts Entry point to your express app
test Contains your tests. Separate 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
.env.example API keys, tokens, passwords, database URI. Clone this, but don't check it in to public repos.
.travis.yml Used to configure Travis CI build
.copyStaticAssets.ts Build script that copies images, fonts, and JS libs to the dist folder
jest.config.js Used to configure Jest running tests written in TypeScript
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
.eslintrc Config settings for ESLint code style checking
.eslintignore Config settings for paths to exclude from linting

Building the project

It 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. 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.

Configuring TypeScript compilation

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": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
        "*": [
            "node_modules/*",
            "src/types/*"
        ]
    }
},
compilerOptions Description
"module": "commonjs" The output module type (in your .js files). Node uses commonjs, so that is what we use
"esModuleInterop": true, Allows usage of an alternate module import syntax: import foo from 'foo';
"target": "es6" The output language level. Node supports ES6, so we can target that here
"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
"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
"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.

Running the build

All the different build steps are orchestrated via npm scripts. Npm scripts basically allow us to call (and chain) terminal commands via npm. 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 npm run <script-name> from the command line. You'll notice that npm 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:

Npm Script Description
build-sass Compiles all .scss files to .css files
build-ts Compiles all source .ts files to .js files in the dist folder
build Full build. Runs ALL build tasks (build-sass, build-ts, lint, copy-static-assets)
copy-static-assets Calls script that copies JS libs, fonts, and images to dist directory
debug Performs a full build and then serves the app in watch mode
lint Runs ESLint on project files
serve-debug Runs the app with the --inspect flag
serve Runs node on dist/server.js which is the apps entry point
start Does the same as 'npm run serve'. Can be invoked with npm start
test Runs tests using Jest test runner
watch-debug The same as watch but includes the --inspect flag so you can attach a debugger
watch-node Runs node with nodemon so the process restarts if it crashes. Used in the main watch task
watch-sass Same as build-sass but continuously watches .scss files and re-compiles when needed
watch-test Runs tests in watch mode
watch-ts Same as build-ts but continuously watches .ts files and re-compiles when needed
watch Runs all watch tasks (TypeScript, Sass, Node). Use this if you're not touching static assets.

Type Definition (.d.ts) Files

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 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 of high quality 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 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!)

Installing .d.ts files from DefinitelyTyped

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 npm install --save-dev @types/jquery.

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.

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 npm 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.

What if a library isn't on DefinitelyTyped?

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).

Setting up TypeScript to look for .d.ts files in another folder

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": {
    "*": [
        "node_modules/*",
        "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 flash from "express-flash";

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 express-flash.d.ts.

Using dts-gen

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. In this project, bcrypt-nodejs.d.ts, fbgraph.d.ts, and lusca.d.ts were all generated using dts-gen.

Writing a .d.ts file

If generating a .d.ts using dts-gen isn't working, you should tell me about it first, but then you can create your own .d.ts file.

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.

Contributing to DefinitelyTyped

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. If you're not interested, you should tell me why so we can help make it easier in the future!

Summary of .d.ts management

In general if you stick to the following steps you should have minimal .d.ts issues;

  1. After installing any npm package as a dependency or dev dependency, immediately try to install the .d.ts file via @types.
  2. If the library has a .d.ts file on DefinitelyTyped, the installation will succeed, and you are done. If the install fails because the package doesn't exist, continue to step 3.
  3. Make sure you project is configured for supplying your own d.ts files
  4. Try to generate a .d.ts file with dts-gen. If it succeeds, you are done. If not, continue to step 5.
  5. Create a file called <some-library>.d.ts in your types folder.
  6. Add the following code:
declare module "<some-library>";
  1. 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.
  2. If you are still having issues, let me know by emailing me or pinging me on twitter, I will help you.

Debugging

Debugging TypeScript is exactly like debugging JavaScript with one caveat, you need source maps.

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.

Configuring source maps

First you need to make sure your tsconfig.json has source map generation enabled:

"compilerOptions" {
    "sourceMap": 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.

Using the debugger in VS Code

Debugging is one of the places where VS Code really shines over other editors. Node.js debugging in VS Code is easy to set up and even easier to use. This project comes pre-configured with everything you need to get started.

When you hit F5 in VS Code, it looks for a top level .vscode folder with a launch.json file.

You can debug in the following ways:

  • Launch Program - transpile typescript to javascript via npm build, then launch the app with the debugger attached on startup
  • 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. We added "protocol": "inspector" which tells VS Code that we're using the latest version of Node which uses a new debug protocol.
  • 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.
  • Jest all - run all tests, set a break point.

In this file, you can tell VS Code exactly what you want to do:

[
        {
            "name": "Launch Program",
            "type": "node",
            "program": "${workspaceFolder}/dist/server.js",
            "request": "launch",
            "preLaunchTask": "npm: build"
        },
        {
            "type": "node",
            "request": "attach",
            "name": "Attach by Process ID",
            "processId": "${command:PickProcess}",
            "protocol": "inspector"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Jest Current File",
            "program": "${workspaceFolder}/node_modules/.bin/jest",
            "args": [
                "${fileBasenameNoExtension}",
                "--detectOpenHandles"
            ],
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "disableOptimisticBPs": true,
            "windows": {
                "program": "${workspaceFolder}/node_modules/jest/bin/jest",
            }
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Jest all",
            "runtimeExecutable": "npm",
            "runtimeArgs": [
                "run-script",
                "test"
            ],
            "port": 9229,
            "skipFiles": [
                "<node_internals>/**"
            ]
        },
    ]

With this file in place, you can hit F5 to attach a debugger. You will probably have multiple node processes running, so you need to find the one that shows node dist/server.js. Now just set your breakpoints and go!

Testing

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.

Install the components

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.

Configure Jest

Jest's configuration lives in jest.config.js, so let's open it up and add the following code:

module.exports = {
    globals: {
        'ts-jest': {
            tsconfigFile: 'tsconfig.json'
        }
    },
    moduleFileExtensions: [
        'ts',
        'js'
    ],
    transform: {
        '^.+\\.(ts|tsx)$': './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.

Running tests

Simply run npm run test. Note this will also generate a coverage report.

Writing tests

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.

ESLint

ESLint is a code linter which mainly helps catch quickly minor code quality and style issues.

ESLint rules

Like most linters, ESLint has a wide set of configurable rules as well as support for custom rule sets. All rules are configured through .eslintrc configuration file. In this project, we are using a fairly basic set of rules with no additional custom rules.

Running ESLint

Like the rest of our build steps, we use npm scripts to invoke ESLint. To run ESLint you can call the main build script or just the ESLint task.

npm run build   // runs full build including ESLint
npm run lint    // runs only ESLint

Notice that ESLint is not a part of the main watch task.

If you are interested in seeing ESLint feedback as soon as possible, I strongly recommend the VS Code ESLint extension.

VSCode Extensions

To enhance your development experience while working in VSCode we also provide you a list of the suggested extensions for working with this project:

Suggested Extensions In VSCode

Dependencies

Dependencies are managed through package.json. In that file you'll find two sections:

dependencies

Package Description
async Utility library that provides asynchronous control flow.
bcrypt-nodejs Library for hashing and salting user passwords.
bluebird Promise library
body-parser Express 4 middleware.
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-validator Easy form validation for Express.
fbgraph Facebook Graph API library.
lodash General utility library.
lusca CSRF middleware.
mongoose MongoDB ODM.
nodemailer Node.js library for sending emails.
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.
request Simplified HTTP request library.
request-promise Promisified HTTP request library. Let's us use async/await
winston Logging library

devDependencies

Package Description
@types Dependencies in this folder are .d.ts files used to provide types
chai Testing utility library that makes it easier to write tests
concurrently Utility that manages multiple concurrent tasks. Used with npm scripts
jest Testing library for JavaScript.
sass Allows to compile .scss files to .css
nodemon Utility that automatically restarts node process when it crashes
supertest HTTP assertion library.
ts-jest A preprocessor with sourcemap support to help use TypeScript with Jest.
ts-node Enables directly running TS files. Used to run copy-static-assets.ts
eslint Linter for JavaScript and TypeScript files
typescript JavaScript compiler/type checker that boosts JavaScript productivity

To install or update these dependencies you can use npm install or npm update.

Hackathon Starter Project

A majority of this quick start's content was inspired or adapted from Sahat's excellent Hackathon Starter project.

License

Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License.

typescript-node-starter's People

Contributors

alan-agius4 avatar amodolo avatar backmeupplz avatar bmiddha avatar brittanydrandolph avatar deilan avatar dependabot[bot] avatar diberry avatar dmt avatar kevguy avatar klemensz avatar konradlinkowski avatar meir017 avatar microsoftopensource avatar msftgits avatar nmchaves avatar nmvikings avatar nyashanziramasanga avatar ofirgeller avatar pavanjadhaw avatar peterblazejewicz avatar rap2hpoutre avatar reecelangerock avatar samal-rasmussen avatar sana-ajani avatar sebastianseilund avatar shanelanan avatar thatkookooguy avatar tioback avatar x4m3 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typescript-node-starter's Issues

RepositoryNotFoundError w/ Express

I have a modified version of the express example that uses the latest version. When referencing the entity class

photos = await getEntityManager().getRepository(Photo).find()

I receive an error, however when using the entity string "Photo"

photos = await getEntityManager().getRepository("Photo").find()

everything works fine. This only occurs inside of the controller class. If I move the same code into the createConnection callback, everything works fine:

createConnection({
    ...configuration
})
    .then(connection => {
        const repo = getEntityManager().getRepository(Photo).find().then(console.log)

        // const app = express()
        // app.use(bodyParser.json())
        // routes.forEach(route => {
        //     app[route.method](route.path, (request: Request, response: Response, next: Function) => {
        //         route.action(request, response).then(() => next).catch(err => next(err))
        //     })
        // })
        // app.listen(3000)
    })

Update of express-validator and source rewrite

The express-validator has been upgrade and its 5.* version explicitly states that API used in this project (and some projects, that part of this project are based on), are deprecated:

The version 3 style of doing validations is still available. Please check the legacy API for the docs.

https://github.com/ctavan/express-validator

There is no easy way to just change the express-validator dependency version up to 5.* without changing some part of code (e.g. validators in user controller).

Can this project source be upgraded? This will break the compatibility with a projects like https://github.com@sahat/hackathon-starter further.

Thanks!

Add an example of nested models

Hi,

I'm struggling to make nested models work, would you mind adding an example?

In my model, I have:
child: string | UserModel

String when the child is not populated, UserModel if populated.

Now if I try to access child.email after population, I get property email does not exist.

Any idea how to fix this?

Many thanks!

`tsconfig.json` does not include correct libraries

With the current setup, it's possible to put this into src/server.ts and it will compile fine:

window.alert('this is not valid in Node');

Normal solution is to put "lib": ["es2015"] into tsconfig.json but this causes many jQuery-related issues in this repo. I only wanted to take a quick look so am not sure about the details but wanted to quickly report this issue with types.

Error during npm start command

Hi guys,

I'm getting following error during npm start command:

`debug: Logging initialized at debug level
debug: Using .env.example file to supply config environment variables
events.js:182
throw er; // Unhandled 'error' event
^

Error: listen EADDRINUSE :::3000
at Object._errnoException (util.js:1019:11)
at _exceptionWithHostPort (util.js:1041:20)
at Server.setupListenHandle [as _listen2] (net.js:1344:14)
at listenInCluster (net.js:1385:12)
at Server.listen (net.js:1469:7)
at Function.listen (/home/user/projects/test/TypeScript-Node-Starter/node_modules/express/lib/application.js:618:24)
at Object. (/home/user/projects/test/TypeScript-Node-Starter/dist/server.js:15:30)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:607:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] serve: node dist/server.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] serve script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/user/.npm/_logs/2018-04-05T09_41_53_909Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: npm run serve
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/user/.npm/_logs/2018-04-05T09_41_53_922Z-debug.log
`

Can somebody help me?

Many thanks.

MongoError: not authorized on admin to execute command { listIndexes: "sessions", cursor: {} }

I installed Mongo according to the instructions at: https://www.howtoforge.com/tutorial/install-mongodb-on-ubuntu-16.04/ and I am getting an error.

[Node] Unhandled rejection MongoError: not authorized on admin to execute command { listIndexes: "sessions", cursor: {} }
[Node] at Function.MongoError.create (/home/ubuntu/projects/project2/node_modules/mongodb-core/lib/error.js:31:11)
[Node] at queryCallback (/home/ubuntu/projects/project2/node_modules/mongodb-core/lib/cursor.js:212:36)
[Node] at /home/ubuntu/projects/project2/node_modules/mongodb-core/lib/connection/pool.js:469:18
[Node] at _combinedTickCallback (internal/process/next_tick.js:131:7)
[Node] at process._tickCallback (internal/process/next_tick.js:180:9)
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] starting node dist/server.js
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] starting node dist/server.js
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] restarting due to changes...
[TypeScript] 19:39:18 - Compilation complete. Watching for file changes.
[TypeScript]
[TypeScript]
[Node] [nodemon] starting node dist/server.js
[Node] App is running at http://localhost:3000 in development mode
[Node] Press CTRL-C to stop
[Node]
[Node] Unhandled rejection MongoError: not authorized on admin to execute command { listIndexes: "sessions", cursor: {} }
[Node] at Function.MongoError.create (/home/ubuntu/projects/project2/node_modules/mongodb-core/lib/error.js:31:11)
[Node] at queryCallback (/home/ubuntu/projects/project2/node_modules/mongodb-core/lib/cursor.js:212:36)
[Node] at /home/ubuntu/projects/project2/node_modules/mongodb-core/lib/connection/pool.js:469:18
[Node] at _combinedTickCallback (internal/process/next_tick.js:131:7)
[Node] at process._tickCallback (internal/process/next_tick.js:180:9)

Build fails when using yarn

The build fails and throws several typescript related errors

image

Steps to reproduce:

yarn install

yarn run build or yarn build

Use mongoose model statics object to add method

by adding static methods to mongoose's schema object it will show how to take advantage of the mongoose.model function even more.
using the function:

function model<T extends Document, U extends Model<T>>

this would require us to create a static method and another type

export type UserSchema = mongoose.Model<UserModel> & {
  someStaticMethod: (arg1: string) => void;
}

and then at the end:

const User = mongoose.model<UserModel, UserSchema>("User", userSchema);

Hello, I don't speak English. I want to describe my question in Chinese, OK?

在学习的过程中看到这段位运算符(&)的代码表示看不懂,能给我解答下这段代码的意义么?
谢谢了。
type UserModel 这是定义的什么类型?
还有就是 mongoose.Document & {} 返回 0 或者 1 ? 但是 一个 {}&{} 的情况下返回的都是0吧?
菜鸟不是很懂。
------------------------------Translation software translation-----------------------------------------------
See the Dan operator in the process of learning (&) code that cannot read, can I answer this code significance?
Thank you。
What type of type UserModel is this defined?
There is a mongoose.Document & {} return 0 or 1? But a {}&{} case returned is 0?
Rookie is not very understanding.

20170609183738

Bootstrap fonts not found

Hello.

You have forgotten to add Bootstrap's fonts into the fonts folder. There are just FontAwesome's fonts in the fonts directory. It founds when using Glyphicons.

Typescript model export not working

Hi,

I can't export my model as my model type. This line gives me this error:

src/model/person.model.ts(19,14): error TS2322: Type 'Model<TUserModel>' is not assignable to type 'TUserModel'.
  Type 'Model<TUserModel>' is not assignable to type 'Document'.
    Property 'increment' is missing in type 'Model<TUserModel>'.

Project no longer works

Latest version of everything (typescript 2.4.1)

Followed instructions, got to npm start, which yields

node_modules/@types/request/index.d.ts(66,15): error TS2430: Interface 'DefaultUriUrlRequestApi<TRequest, TOptions, TUriUrlOptions>' incorrectly extends interface 'RequestAPI<TRequest, TOptions, TUriUrlOptions>'.
  Types of property 'defaults' are incompatible.

Error on Win 10

On Win 10 I get an error when I run "npm start"

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "watch"
npm ERR! node v6.9.5
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] watch: `concurrently -k -p "[{name}]" -n "Sass,TypeScript,Node" -c "yellow.bold,cyan.bold,green.bold" "npm run watch-sass" "npm run watch-ts" "nodemon dist/server.js"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] watch script 'concurrently -k -p "[{name}]" -n "Sass,TypeScript,Node" -c "yellow.bold,cyan.bold,green.bold" "npm run watch-sass" "npm run watch-ts" "nodemon dist/server.js"'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the express-typescript-starter package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     concurrently -k -p "[{name}]" -n "Sass,TypeScript,Node" -c "yellow.bold,cyan.bold,green.bold" "npm run watch-sass" "npm run watch-ts" "nodemon dist/server.js"

Forked and created a REST API starter

Hi guys,
I've forked this awesome starter project and created a starter for a REST API:
TypeScript REST Node Starter
It has a basic JWT authentication and activation using SMTP without passport. It needs improvements (Swagger integration, tests, password expiry handling, and general code improvements).
My question is should we, after needed improvements, at some point create a pull request on a new branch of this project where i think that code belongs?
I would appreciate if someone can review and advise, thanks!

Using yarn (instead of npm) leads to typescript compilation errors

See https://asciinema.org/a/IARDsufZ2CEYvfuvDAUogExGz

Doing yarn install && yarn start leads to compile error.

Doing npm install && npm run lead to fine running node application.

> tsc

node_modules/@types/connect-mongo/node_modules/@types/express-session/index.d.ts(36,7): error TS2300: Duplicate identifier 'serialize'.
node_modules/@types/connect-mongo/node_modules/@types/express-session/index.d.ts(41,7): error TS2300: Duplicate identifier 'regenerate'.
node_modules/@types/connect-mongo/node_modules/@types/express-session/index.d.ts(42,7): error TS2300: Duplicate identifier 'destroy'.
node_modules/@types/connect-mongo/node_modules/@types/express-session/index.d.ts(43,7): error TS2300: Duplicate identifier 'reload'.
node_modules/@types/connect-mongo/node_modules/@types/express-session/index.d.ts(44,7): error TS2300: Duplicate identifier 'save'.
node_modules/@types/connect-mongo/node_modules/@types/express-session/index.d.ts(45,7): error TS2300: Duplicate identifier 'touch'.
node_modules/@types/express-session/index.d.ts(21,5): error TS2300: Duplicate identifier 'regenerate'.
node_modules/@types/express-session/index.d.ts(22,5): error TS2300: Duplicate identifier 'destroy'.
node_modules/@types/express-session/index.d.ts(23,5): error TS2300: Duplicate identifier 'reload'.
node_modules/@types/express-session/index.d.ts(24,5): error TS2300: Duplicate identifier 'save'.
node_modules/@types/express-session/index.d.ts(25,5): error TS2300: Duplicate identifier 'touch'.
node_modules/@types/express-session/index.d.ts(37,5): error TS2300: Duplicate identifier 'serialize'.

Project Structure Regarding

How is the structure of the project created ? Are you using some kind of express-generator or is it manual creation ?

Deploy on Azure Web Apps

When I try to deploy this starter on Azure Web Apps, I get the following error on deployment:

Invalid start-up command "npm run build && npm run watch" in package.json. Please use the format "node <script relative path>".
Looking for app.js/server.js under site root.
Missing server.js/app.js files, web.config is not generated

What's the best way to do this?

adding new modules

I have a problem with adding new npm modules like method-override, helmet and winston-express-middleware
I tried adding new modules with npm install --save @types/winnston-express-middleware
but there is an npm Error: "npm ERR! 404 Not Found: @types/winston-express-middleware@latest"
"[ts] Could not find a declaration file for module 'winnston-express-middleware'.
" error TS7016: Could not find a declaration file for module 'winston-express-middleware'."
these is the case the all modules I tried to add.

mongo setup not working

I am new to this stack and would like my starter to work "out of the box".

I installed mongodb like so:

https://www.howtoforge.com/tutorial/install-mongodb-on-ubuntu-16.04/

When I try to run it I get:

$ npm start

> [email protected] start /home/ubuntu/projects/project2
> npm run build && npm run watch


> [email protected] build /home/ubuntu/projects/project2
> npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets


> [email protected] build-sass /home/ubuntu/projects/project2
> node-sass src/public/css/main.scss dist/public/css/main.css

Rendering Complete, saving .css file...
Wrote CSS to /home/ubuntu/projects/project2/dist/public/css/main.css

> [email protected] build-ts /home/ubuntu/projects/project2
> tsc


> [email protected] tslint /home/ubuntu/projects/project2
> tslint -c tslint.json -p tsconfig.json




> [email protected] copy-static-assets /home/ubuntu/projects/project2
> node copyStaticAssets.js


> [email protected] watch /home/ubuntu/projects/project2
> concurrently -k -p "[{name}]" -n "Sass,TypeScript,Node" -c "yellow.bold,cyan.bold,green.bold" "npm run watch-sass" "npm run watch-ts" "npm run serve"

[Node] 
[Node] > [email protected] serve /home/ubuntu/projects/project2
[Node] > nodemon dist/server.js
[Node] 
[TypeScript] 
[TypeScript] > [email protected] watch-ts /home/ubuntu/projects/project2
[TypeScript] > tsc -w
[TypeScript] 
[Sass] 
[Sass] > [email protected] watch-sass /home/ubuntu/projects/project2
[Sass] > node-sass -w src/public/css/main.scss dist/public/css/main.css
[Sass] 
[Node] [nodemon] 1.11.0
[Node] [nodemon] to restart at any time, enter `rs`
[Node] [nodemon] watching: *.*
[Node] [nodemon] starting `node dist/server.js`
[Node] Unhandled rejection MongoError: not authorized on admin to execute command { listIndexes: "sessions", cursor: {} }
[Node]     at Function.MongoError.create (/home/ubuntu/projects/project2/node_modules/mongodb-core/lib/error.js:31:11)
[Node]     at queryCallback (/home/ubuntu/projects/project2/node_modules/mongodb-core/lib/cursor.js:212:36)
[Node]     at /home/ubuntu/projects/project2/node_modules/mongodb-core/lib/connection/pool.js:469:18
[Node]     at _combinedTickCallback (internal/process/next_tick.js:131:7)
[Node]     at process._tickCallback (internal/process/next_tick.js:180:9)
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] starting `node dist/server.js`
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] starting `node dist/server.js`
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] starting `node dist/server.js`
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] restarting due to changes...
[TypeScript] 21:13:36 - Compilation complete. Watching for file changes.
[TypeScript] 
[TypeScript] 
[Node] [nodemon] restarting due to changes...
[Node] [nodemon] starting `node dist/server.js`
[Node] Unhandled rejection MongoError: not authorized on admin to execute command { listIndexes: "sessions", cursor: {} }
[Node]     at Function.MongoError.create (/home/ubuntu/projects/project2/node_modules/mongodb-core/lib/error.js:31:11)
[Node]     at queryCallback (/home/ubuntu/projects/project2/node_modules/mongodb-core/lib/cursor.js:212:36)
[Node]     at /home/ubuntu/projects/project2/node_modules/mongodb-core/lib/connection/pool.js:469:18
[Node]     at _combinedTickCallback (internal/process/next_tick.js:131:7)
[Node]     at process._tickCallback (internal/process/next_tick.js:180:9)

As you can see Mongo is giving me an error.

problem with npm start

Its not creating dist folder when I use npm start.
got an error that "Error: Cannot find module 'C:\Users\TypeScript-Node-Starter-master\dist\server.js'"
when start debugging in VS got an error that "Debugging with legacy protocol because Node.js version could not be determined (Error: connect ECONNREFUSED 127.0.0.1:9229)"

tsconfig paths of node_modules/* not referenced in readme

Noticed in the readme you only mentioned tconfig paths for src/types, but in your tsconfig you have node_modules/* even though you mentioned in the readme that node_modules/@types is already a default.

Is this a check for any types included within their own packages, or a mistake?

By the way thanks so much for this repo. I have gone through it all piece by piece while referencing your readme so I can pull over my new TypeScript skills from Angular into Node/Express. Your readme is the gold star for getting up and going with Node and TypeScript, as well as npm scripts, best practices, and helpful associated packages.

supertest tests always pass

changing any of the expected status codes to other values does not seem to have any impact on whether or not the tests pass.

Digging a bit further, I can't get any done callback based test to work. The only thing that seems to work right is returning the result of the expect call. (After also adjusting the supertest initialisation to point to port 3000).

I'm new to TypeScript, Node and these test frameworks so I might just be missing something but the fact that you can change the status codes for expectations and the tests still pass seems wrong either way.

mongo steps

For users who are just setting up mongo, they cant just run 'mongod', they run into errors. It's worth calling out that they first needed to run:
sudo mkdir -p /data/db //this creates the db directory
sudo chmod 777 /data/db //this gives the db correct read/write permissions

Before they can get up and go. Worth putting in for saving other newbies a few stackoverflow searches.

Sources:
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
https://stackoverflow.com/questions/28987347/setting-read-write-permissions-on-mongodb-folder/29003511

Bug in controllers/user.ts

Problem: Messages Email ${email} not found. and "Invalid email or password." do not show up.
Solution: Line 44 in controllers/user.ts should be
req.flash("errors", { msg: info.message });
instead of
req.flash("errors", info );

[Question] Deployment of dist folder in production

I am using this repo for a api-based nodejs based application, so I'd basically be returning json objects from the application.

The npm build command generates a dist folder with compiled javascript files and the npm serve commands make use of the server.js from the dist folder.
While development, I am using nodemon and ts-node to compile typescript files on the fly, but do I use it in production enviroment?

How do i deploy the application? Do I have to copy the package.json into the dist folder, copy the contents of dist folder to server location, then do a npm install? Or do I use the entire project itself and use typescript in the deployment environment as well?

Error: Unknown authentication strategy "local"

When running the app as cloned, I got Error: Unknown authentication strategy "local" from

controllers/user.ts line 41:
passport.authenticate("local", ...

I remedied it by importing the configured passport instance from config/passport.ts.

Added export default passport; to the end of config/passport.ts so that I could import it in controllers/user.ts

import { default as passport } from '../config/passport'

I'm curious, I presume the error is because I'm doing something wrong, just not sure what ¯_(ツ)_/¯

[EDIT] also had to add app.use(passport.initialize()); to app.ts 🤔

Need redeploy/update app README steps

It would be great to add in README steps for redeploy / updating yet deployed app. Becase its not clear - there is no such stuff in interface or context menus of VS Code extension

Error on npm start

Hello, I copied the repo down, ran npm install, run npm start, and this is what I get.

npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
npm ERR! node v6.10.1
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] build: `npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script 'npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the express-typescript-starter package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs express-typescript-starter
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls express-typescript-starter
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\alexw\Source\treetone\npm-debug.log

npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.10.1
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `npm run build && npm run watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script 'npm run build && npm run watch'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the express-typescript-starter package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run build && npm run watch
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs express-typescript-starter
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls express-typescript-starter
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\alexw\Source\treetone\npm-debug.log

build fails

I have followed the basic instructions on the readme, but I can't get a basic build.

npm ERR! Failed at the [email protected] build script 'npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the express-typescript-starter package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets

running: tsc
node_modules/@types/jest/index.d.ts(7,13): error TS2300: Duplicate identifier 'beforeAll'.
node_modules/@types/jest/index.d.ts(8,13): error TS2300: Duplicate identifier 'beforeEach'.
node_modules/@types/jest/index.d.ts(9,13): error TS2300: Duplicate identifier 'afterAll'.
node_modules/@types/jest/index.d.ts(10,13): error TS2300: Duplicate identifier 'afterEach'.
node_modules/@types/jest/index.d.ts(11,13): error TS2300: Duplicate identifier 'describe'.
node_modules/@types/jest/index.d.ts(12,13): error TS2300: Duplicate identifier 'fdescribe'.
node_modules/@types/jest/index.d.ts(13,13): error TS2300: Duplicate identifier 'xdescribe'.
node_modules/@types/jest/index.d.ts(14,13): error TS2300: Duplicate identifier 'it'.
node_modules/@types/jest/index.d.ts(15,13): error TS2300: Duplicate identifier 'fit'.
node_modules/@types/jest/index.d.ts(16,13): error TS2300: Duplicate identifier 'xit'.
node_modules/@types/jest/index.d.ts(20,15): error TS2451: Cannot redeclare block-scoped variable 'expect'.
node_modules/@types/jest/index.d.ts(339,45): error TS2314: Generic type 'ObjectContaining' requires 1 type argument(s).
node_modules/@types/jest/index.d.ts(368,15): error TS2428: All declarations of 'ObjectContaining' must have identical type parameters.
node_modules/@types/jest/index.d.ts(431,15): error TS2300: Duplicate identifier 'CustomMatcherFactory'.
node_modules/@types/jest/index.d.ts(441,15): error TS2300: Duplicate identifier 'CustomEqualityTester'.
../../../node_modules/@types/jasmine/index.d.ts(15,18): error TS2300: Duplicate identifier 'describe'.
../../../node_modules/@types/jasmine/index.d.ts(16,18): error TS2300: Duplicate identifier 'fdescribe'.
../../../node_modules/@types/jasmine/index.d.ts(17,18): error TS2300: Duplicate identifier 'xdescribe'.
../../../node_modules/@types/jasmine/index.d.ts(26,18): error TS2300: Duplicate identifier 'it'.
../../../node_modules/@types/jasmine/index.d.ts(35,18): error TS2300: Duplicate identifier 'fit'.
../../../node_modules/@types/jasmine/index.d.ts(36,18): error TS2300: Duplicate identifier 'xit'.
../../../node_modules/@types/jasmine/index.d.ts(51,18): error TS2300: Duplicate identifier 'beforeEach'.
../../../node_modules/@types/jasmine/index.d.ts(58,18): error TS2300: Duplicate identifier 'afterEach'.
../../../node_modules/@types/jasmine/index.d.ts(66,18): error TS2300: Duplicate identifier 'beforeAll'.
../../../node_modules/@types/jasmine/index.d.ts(74,18): error TS2300: Duplicate identifier 'afterAll'.
../../../node_modules/@types/jasmine/index.d.ts(80,18): error TS2451: Cannot redeclare block-scoped variable 'expect'.
../../../node_modules/@types/jasmine/index.d.ts(86,18): error TS2451: Cannot redeclare block-scoped variable 'expect'.
../../../node_modules/@types/jasmine/index.d.ts(92,18): error TS2451: Cannot redeclare block-scoped variable 'expect'.
../../../node_modules/@types/jasmine/index.d.ts(171,9): error TS2375: Duplicate number index signature.
../../../node_modules/@types/jasmine/index.d.ts(181,15): error TS2428: All declarations of 'ObjectContaining' must have identical type parameters.
../../../node_modules/@types/jasmine/index.d.ts(212,10): error TS2300: Duplicate identifier 'CustomEqualityTester'.
../../../node_modules/@types/jasmine/index.d.ts(219,10): error TS2300: Duplicate identifier 'CustomMatcherFactory'.
../../../node_modules/@types/jasmine/index.d.ts(222,9): error TS2374: Duplicate string index signature.
../../../node_modules/@types/jasmine/index.d.ts(227,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'message' must be of type 'string | (() => string)', but here has type 'string'.
../../../node_modules/@types/jasmine/index.d.ts(227,9): error TS2687: All declarations of 'message' must have identical modifiers.

istanbul or?

Thank you very much for the example. Could you extend it to show best practice for code coverage?

Express Interface Imports for Improved Type Safety

For improved type annotations would it be a good idea to import the express interfaces from Definitely Typed Express library to improve type safety? It also serves as documentation even though it is a bit more verbose.

import express = require( 'express');
import { 
  Application, Request, Response, NextFunction 
} from 'express';

var app: Application = express();

// ... removed for brevity

app.use(
  ( error: any, request: Request, response: Response, next: NextFunction ) : void => {
    // ... removed for brevity
  }
);

Issue with WebStorm with "esModuleInterop": true

I noticed this a few days ago when exploring using WebStorm. Previously, I had used Visual Studio Code with this starter repo's tsconfig.json file. Everything worked fine. But in order for WebStorm's "compile typescript" pre-launch task to work, I had to remove the "esModuleInterop": true property from this tsconfig.json file (and return to using the import * as x from 'y'; import style instead of the import x from 'y'; style that this property allowed. In WebStorm, before removing this property, the compile step is skipped, and the launch task attempts to run and then fails since the dist directory is still empty (no compilation occurred).

Dev Dependencies section in README file there's some items that has a wrong description

First of all, great work with this project by the way. Its been so helpful in my way to learn typescript.
now...
In the #devdepencies-1 section of the README, some items has a wrong description.

jest -> Reports real-time server metrics for Express.
node-sass -> GitHub API library.
ts-test -> Instagram API library.

I take the liberty of open a PR to solved this.

Thanks!

cannot build

After running yarn install, i run the build.
yarn run build returns the following error:

$ yarn run build
yarn run v0.27.5
$ npm run build-sass && npm run build-ts && npm run tslint && npm run copy-static-assets
module.js:471
    throw err;
    ^

Error: Cannot find module '../lib/utils/unsupported.js'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at /usr/local/lib/node_modules/npm/bin/npm-cli.js:19:21
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:92:3)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
`
``

Question about user side variables

Helllo,

I have noticed that the templates used variables that weren't sent down via render e.g:

export let getAccount = (req: Request, res: Response) => {
  res.render("account/profile", {
    title: "Account Management"
  });
};

but user info is used in the pug template: user.profile.name

    .form-group
      label.col-sm-3.control-label(for='name') Name
      .col-sm-7
        input.form-control(type='text', name='name', id='name', value=**_## user.profile.name_**)
    .form-group

How did that variable apear on the client side?

Thank you for the answer!

Laci

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.