Git Product home page Git Product logo

express-generator-typescript's Introduction

overnightjs

Express with TypeScript's application generator.

NPM Version Package License NPM Downloads

What is it?

Creates a new express application similar to the express-generator module. Except this new application is configured to use TypeScript instead of plain JavaScript.

This project complies with Typescript best practices listed here.

Why express-generator-typescript?

NodeJS is great for the rapid development of web-projects, but is often neglected because of the lack of type safety. TypeScript solves this issue and (along with its linter file) can even make your code more robust than some other static languages like Java.

There are some other tools out there to generate express apps with TypeScript such as express-generator-ts, but these either haven't been updated in a while or install a lot of junk in your project (such as an ORM).

Due to the heavy use of single-page-applications, no view-engine is configured by default. Express is only setup with the minimal settings for calling APIs and serving an index.html file. All the tools you need to run for development (while restarting on changes), building, testing, and running for production are packaged with this library.

In addition, relative paths are also setup, so you don't have to go through the trouble of installing and configuring tsconfig-paths and module-alias. Just make sure to update paths in tsconfig.json and _moduleAliases in package.json if you want to add/edit the relative paths.

Sample-project

When you run express-generator-typescript, it sets up a simple application with routes for adding, updating, deleting, and fetching user objects. This is just to demonstrate how routing is done with express.

If you want a fully-secure application, you can pass the --with-auth option and you will have an application which requires you to login before calling APIs on user objects. The app is configured with production quality client-side security and uses signed-cookies and jsonwebtokens to store user-session data. If you're new to web-development and still learning about securing websites, I highly encourage to use this option.

Installation

$ Just use 'npx'
  Or
$ npm install -g express-generator-typescript

Quick Start

The quickest way to get started is use npx and pass in the name of the project you want to create. If you don't specify a project name, the default express-gen-ts will be used instead. If you want to use yarn instead of npm, pass the option --use-yarn.

Create the app:
With no options: $ npx express-generator-typescript
With all options (order doesn't matter): $ npx express-generator-typescript --with-auth --use-yarn "project name"

Start your express-generator-typescript app in development mode at http://localhost:3000/:

$ cd "project name" && npm run dev

Available commands for the server.

  • Run the server in development mode: npm run dev.
  • Run all unit-tests with hot-reloading: npm test.
  • Run a single unit-test: npm test -- --testFile="name of test file" (i.e. --testFile=Users).
  • Run all unit-tests without hot-reloading: npm run test:no-reloading
  • Check for linting errors: npm run lint.
  • Build the project for production: npm run build.
  • Run the production build: npm start.
  • Run production build with a different env file npm start -- --env="name of env file" (default is production).

Debugging

During development, express-generator-typescript uses nodemon to restart the server when changes are detected. If you want to enable debugging for node, you'll need to modify the nodemon configurations. This is located under nodemonConfig: in package.json for the server and ./spec/nodemon.json for unit-testing. For the exec property, replace ts-node with node --inspect -r ts-node/register.

Note for VS-Code users

A lot of users have asked about launch.json configurations for running this in VS-Code, so here's a snippet of the launch.json configuration you need to bypass nodemon and run directly with VS-Code.

  {
        "type": "pwa-node",
        "request": "launch",
        "name": "Debug Dev Env",
        "runtimeArgs": [
            "-r",
            "ts-node/register",
            "-r",
            "tsconfig-paths/register",
        ],
        "args": [
            "${workspaceFolder:express-gen-ts}/src/index.ts"
        ],
        "resolveSourceMapLocations": [
            "${workspaceFolder}/**",
            "!**/node_modules/**"
        ],
   }

Note for windows users

If you are on Windows, the bcrypt module tends to be fussy. To use this module on Windows you need to make sure you have the node Windows build tools installed. I don't want to post instructions because they might change frequently. I would search the Microsoft docs on how to setup Node for Windows. To be able to debug in VSCODE on windows I also had to install the node-gyp module globally as well.

Happy web deving :)

License

MIT

express-generator-typescript's People

Contributors

arapl3y avatar dependabot[bot] avatar donnyst avatar hackinteach avatar hemant6488 avatar larvanitis avatar marcus-rise avatar royshea avatar sean-concourse avatar seanpmaxwell avatar thehanna avatar thehaseebahmed 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

express-generator-typescript's Issues

npm run build doesn't work - Windows

Hi. When I run 'npm run build' I get the following error:

[email protected] build
./node_modules/.bin/ts-node build.ts

'.' is not recognized as an internal or external command, operable program or batch file.

I am running this from a Windows machine at the project route.

The odd part is that this worked from my MacBook.
Build Error

Edit: O/S is Windows 11

Thanks.

npm run start is stuck

I have not done anything special. Just generated a new project, added sentry and swagger. Everything runs fine with npm run start:dev but for some reason, npm run start runs and is stuck there indefinitely.

image

Any idea what I might be doing wrong?

'ts-node' is not recognized as an internal or external command, operable program or batch file.

I am on Windows 10.
NPM v7.5.1
Node v15.8.0

$ npm run start:dev

> [email protected] start:dev
> nodemon

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src\**\*
[nodemon] watching extensions: ts,html
[nodemon] starting `ts-node -r tsconfig-paths/register ./src`
'ts-node' is not recognized as an internal or external command,
operable program or batch file.
[nodemon] app crashed - waiting for file changes before starting...

I change the package.json file nodemonConfig to specify the path.

"nodemonConfig": {
    "watch": [
        "src"
    ],
    "ext": "ts, html",
    "ignore": [
        "src/public"
    ],
    "exec": "./node_modules/.bin/ts-node -r tsconfig-paths/register ./src"
},

It works.

$ npm run start:dev

> [email protected] start:dev
> nodemon

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src\**\*
[nodemon] watching extensions: ts,html
[nodemon] starting `./node_modules/.bin/ts-node -r tsconfig-paths/register ./src`

Production Mode not working

right after installing template the production mode is not working :

  1. use npx express-generator-typescript sanitytest to create the template.
  2. compile the application with npm run build
  3. run the application in production mode with npm run start
  4. on a different system connect to the web server on port 8081
    the application will not work correctly, even the css file are not loaded correctly:
    image

webstorm debug get error!

src/routes/middleware.ts(23,17): error TS2339: Property 'sessionUser' does not exist on type 'Response<any, Record<string, any>>

A little help with sending only json response

Hi, I am trying out this generator, and so far, I like what I see. Thing is, I as I am trying to implement my routes, which are similar to the users (res.status(OK).json({users}), but mine never seems to call.

I checked the BaseRouter through console.log and see the regex of my route. For simplicities sake, I have added one route to the index.ts file (where the routes are). So under the

import UserRouter from './routes;
I added my own
import MyThingRouter from './routes; and also router.use('/mything', MyThingRouter);
and myThingRouter does an export default router too.

So still, I got the default users page (html). Thing is, I don't want to send an html/frontend stuff. Only JSON.
I compared this app to my expressjs-generator generated app, and noticed a few things I need clarification on.

  1. Like my ide shows the proper router when I hover over BaseRouter. I'm guessing that it was declared in a 'short-hand' way like instead of using import * as BaseRouter... because of default?
    Either way, BaseRouter seem to know about my route.

  2. How would I be able to send out my json from my routes. In the server.ts, I see the way the example app does it is through sending a template file that has js to 'call/fetch' the user json. I just want to call my route method directly from the browser address. Like
    localhost:3000/mything/all should send my json data.

If I comment out the provided server.js app.get('*', (req, res)... near the end of the file, I get a 404 error "Cannot GET /mything/all". I would have thought that the
app.use('/api', BaseRouter) would handle the route. My expressjs app seems to handle it.

I just tried as of typing this, trying to implement the expressjs way, but the router doesn't seem to call my get method which is almost exactly like the user example in router.get('/all',...). Also, added raw json to res.json in my route, and removing promises because I am somewhat at a loss. Everything is back to default now.

TLdr; I followed the example code and also attempted to implement routing similar to my non-ts expressjs app, but cannot call my get method to return JSON only.

Build exits cleanly even if there are errors

In build.ts when there is an error, the script simply logs it without exiting with a non-zero exit code.

This causes build systems to continue with the build process even though the code may not compile.

A process.exit(1) after the log should fix this.

Add VSCode launch.json to README.md

I'd like to suggest to add your VSCode launch.json config mentioned here #20 to README.md - with a little modification:

When debugging using that launch.json, VSCode issues an error:

`Could not read source map for file:///path/to/your/express-gen-ts/node_modules/typescript/lib/typescript.js: ENOENT: no such file or directory, open 'path\to\your\express-gen-ts\node_modules\typescript\lib\typescript.js.map'`.

This was resolved in VSCode issue #102042, and thus we get the following launch.json:

  {
        "type": "pwa-node",
        "request": "launch",
        "name": "Debug Dev Env",
        "runtimeArgs": [
            "-r",
            "ts-node/register",
            "-r",
            "tsconfig-paths/register",
        ],
        "args": [
            "${workspaceFolder:express-gen-ts}/src/index.ts"
        ],
        "resolveSourceMapLocations": [
            "${workspaceFolder}/**",
            "!**/node_modules/**"
        ],
   }

windows error: 'ENV_FILE' is not recognized as an internal or external command

Hi, I just created a new app using command npx express-generator-typescript api. I really like the setup, thanks for creating it.
I also had an issue running it in on windows, as follows.

[nodemon] starting ENV_FILE=development ts-node -r ./env -r tsconfig-paths/register src/Start.ts
'ENV_FILE' is not recognized as an internal or external command,
operable program or batch file.
[nodemon] app crashed - waiting for file changes before starting...

Just thought i will let you know of the issue and the steps I took to resolve it in my sample project:

  1. install npm install --save-dev cross-env
  2. search for 3 entries for ENV_FILE= and replaced with cross-env ENV_FILE=, thats it.. verbatim like that..

happy to do a PR if you are okay with the choices..

also, I am able to use this project without the above changes in my Windows Subsystem for Linux (WSL) bash shell.. so, it is optional mostly, just in case..

Add support for nodemon debugging

Solid boilerplate, thank you
But i wasn't able to implement nodemon debugging (when debugger reconnects when you change code).
I've spent several hours to follow this article, but wasn't able to make module-aliasing work.

Missing tslib and jsonfile as runtime dependencies

I'm building an app and packaging it in a docker container. In that container I'm only installing npm prod deps not any packages from devDependencies. I'm getting errors about the missing modules when I try to run npm start. Here's a minimal repro to simulate the environment. The second npm install doesn't install tslib and jsonfile.

npx express-generator-typescript my-app
cd my-app
echo "{}" > src/public/test.json
npm install
npm run build
# This works
npm start
rm -rf node_modules
npm install --only=prod
# This doesn't work
npm start

The jsonfile is needed at runtime because I'm serving static json files.
Adding "tslib": "^2.0.0" to dependencies and moving the jsonfile line from devDependencies to dependencies in package.json fixes both of these issues.

npm run start:dev got errors of jet-logger

I got the following error after "npx express-generator-typescript app_name" and "npm run start:dev".

    return new TSError(diagnosticText, diagnosticCodes);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/shared/Logger.ts:10:5 - error TS2304: Cannot find name 'thirdPartyLoggingApp'.

10     thirdPartyLoggingApp.doStuff(...);
       ~~~~~~~~~~~~~~~~~~~~
src/shared/Logger.ts:10:37 - error TS1109: Expression expected.

10     thirdPartyLoggingApp.doStuff(...);
                                       ~

    at createTSError (D:\Repos\ScriptLab\react\express_type_app\node_modules\ts-node\src\index.ts:750:12)
    at reportTSError (D:\Repos\ScriptLab\react\express_type_app\node_modules\ts-node\src\index.ts:754:19)
    at getOutput (D:\Repos\ScriptLab\react\express_type_app\node_modules\ts-node\src\index.ts:941:36)
    at Object.compile (D:\Repos\ScriptLab\react\express_type_app\node_modules\ts-node\src\index.ts:1243:30)
    at Module.m._compile (D:\Repos\ScriptLab\react\express_type_app\node_modules\ts-node\src\index.ts:1370:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (D:\Repos\ScriptLab\react\express_type_app\node_modules\ts-node\src\index.ts:1374:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
  diagnosticText: "\x1B[96msrc/shared/Logger.ts\x1B[0m:\x1B[93m10\x1B[0m:\x1B[93m5\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS2304: \x1B[0mCannot find name 'thirdPartyLoggingApp'.\r\n" +
    '\r\n' +
    '\x1B[7m10\x1B[0m     thirdPartyLoggingApp.doStuff(...);\r\n' +
    '\x1B[7m  \x1B[0m \x1B[91m    ~~~~~~~~~~~~~~~~~~~~\x1B[0m\r\n' +
    '\x1B[96msrc/shared/Logger.ts\x1B[0m:\x1B[93m10\x1B[0m:\x1B[93m37\x1B[0m - \x1B[91merror\x1B[0m\x1B[90m TS1109: \x1B[0mExpression expected.\r\n' +
    '\r\n' +
    '\x1B[7m10\x1B[0m     thirdPartyLoggingApp.doStuff(...);\r\n' +
    '\x1B[7m  \x1B[0m \x1B[91m                                    ~\x1B[0m\r\n',
  diagnosticCodes: [ 2304, 1109 ]
}
[nodemon] app crashed - waiting for file changes before starting...

To fix, I changed src/shared/Logger.ts to the followings, but I assume this is temporary fix.

import logger from 'jet-logger';

export default logger;

Error when using --with-auth option and, no bcrypt binary available and no build tools

I am running the express-generator-typescript tool on Windows, via npx express-generator-typescript --with-auth "my-app-name". I am getting the following error:

npm i -s express dotenv http-status-codes morgan cookie-parser winston module-alias command-line-args bcrypt randomstring jsonwebtoken

By running the verbose version of the above npm command manually I eventually worked out that it was the bcrypt package that was causing the problem because I didn't have the build tools installed. Would it be possible to add some clearer error messages so that this failure case is easier to diagnose?

How to Debugging by VSCode

Hi, im Node newbie.
How do I debug this project with VSCode?

I made the following preparations.

  1. Add nodemon.debug.json
  2. Create launch.json
  3. npm i cross-env
  4. npm i -g node-gyp
  5. npm run start:dev
  6. Set break point on src\routes\Users.ts
  7. Press F5
  8. Launch Chrome
  9. Access to http://localhost/api/users/all
  10. Breakpoint not work
  • nodemon.debug.json
{
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/public"],
  "inspect": true,
  "exec": "cross-env NODE_OPTIONS='--inspect' ts-node -r tsconfig-paths/register ./src --env=development"
}
  • launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "run debug",
      "runtimeArgs": [ "-r", "ts-node/register", "-r", "tsconfig-paths/register", ],
      "args": [ "${workspaceFolder}/src/index.ts" ],
      "protocol": "inspector",
    }
  ]
}
  • Users.ts
router.get('/all', async (req: Request, res: Response) => {
    try {
        const users = 'aaa'; // add Break point🛑
        return res.status(OK).json({users});
    } catch (err) {
        logger.error(err.message, err);
        return res.status(BAD_REQUEST).json({
            error: err.message,
        });
    }
});

VSCode: Parsing error at line 1 col 1 of every ts file

I created a new project with:

$ cd projects
$ express-generator-typescript --socket-io "crudn"

and then opened it in Visual Studio Code (Linux). VSCode underlines in red every 1st character of every ts file and complains with:

Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
The file does not match your project config: ../../../../projects/crudn/src/index.ts.
The file must be included in at least one of the projects provided.

What's next?

Tests are not running in a new created repo

Hi there!

Note: this behavior is happening with the last Mac Monterey release and NodeJS 12 and 16.

In a new repo just recently created the tests are not running
To reproduce this issue just create a new repo with 'express-generator-typescript myrepo' for instance and try to run the tests with 'npm run test'

The error I am receiving is this:

image

If I try to fix the type error changing null with undefined and restart:

image

This is what I am receiving:

image

If I also try to remove the deprecated function:

image

This is what happens:

image

Getting an error when calling "jsonwebtoken.verify"

Just ran the generator. The generated app is throwing an error src/shared/JwtService.ts - the jsonwebtoken.verify has parameters that aren't matching.

I'm running Win10, Node v12, Typescript 3.6.3.

The error message:

`src/shared/JwtService.ts:45:51 - error TS2769: No overload matches this call.
Overload 1 of 3, '(token: string, secretOrPublicKey: Secret, options?: VerifyOptions | undefined): string | object', gave the following error.
Type '(err: VerifyErrors, decoded: string | object) => void' has no properties in common with type 'VerifyOptions'.
Overload 2 of 3, '(token: string, secretOrPublicKey: string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret, callback?: VerifyCallback | undefined): void', gave the following error.
Argument of type '(err: VerifyErrors, decoded: object | string) => void' is not assignable to parameter of type 'VerifyCallback'.
Types of parameters 'err' and 'err' are incompatible.
Type 'JsonWebTokenError | NotBeforeError | TokenExpiredError | null' is not assignable to type 'VerifyErrors'.
Type 'null' is not assignable to type 'VerifyErrors'.
Overload 3 of 3, '(token: string, secretOrPublicKey: string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret, options?: VerifyOptions | undefined, callback?: VerifyCallback | undefined): void', gave the following error.
Type '(err: VerifyErrors, decoded: string | object) => void' has no properties in common with type 'VerifyOptions'.

45 jsonwebtoken.verify(jwt, this.secret, (err: VerifyErrors, decoded: object | string) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

at createTSError (C:\code\js\fullstack_express\express_test\node_modules\ts-node\src\index.ts:434:12)
at reportTSError (C:\code\js\fullstack_express\express_test\node_modules\ts-node\src\index.ts:438:19)
at getOutput (C:\code\js\fullstack_express\express_test\node_modules\ts-node\src\index.ts:578:36)
at Object.compile (C:\code\js\fullstack_express\express_test\node_modules\ts-node\src\index.ts:775:32)
at Module.m._compile (C:\code\js\fullstack_express\express_test\node_modules\ts-node\src\index.ts:858:43)
at Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Object.require.extensions.<computed> [as .ts] (C:\code\js\fullstack_express\express_test\node_modules\ts-node\src\index.ts:861:12)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)`

Jasmine extension failing with "Cannot use import statement outside a module"

The extension Jasmine Test Explorer is failing on a fresh new generated project:

Step to reproduce:

npx express-generator-typescript test

Jasmine Tests output:

(node:75786) UnhandledPromiseRejectionWarning: /private/tmp/test/spec/tests/users.spec.ts:1
import supertest from 'supertest';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:988:16)
    at Module._compile (internal/modules/cjs/loader.js:1036:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Loader.requireShim [as require_] (/Users/yourmum/.vscode/extensions/hbenl.vscode-jasmine-test-adapter-1.7.1/node_modules/jasmine/lib/loader.js:35:3)
    at /Users/yourmum/.vscode/extensions/hbenl.vscode-jasmine-test-adapter-1.7.1/node_modules/jasmine/lib/loader.js:28:12
    at new Promise (<anonymous>)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:75786) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:75786) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I found a few hints online about the same error but nothing's solving it for me...

$ node --version
v14.17.6

Project setup error

First of all, thanks for your work.

Running npx express-generator-typescript on my Windows 10 fails with an Unexpected end of JSON input error. Node 12.18.0 LTS.

$ npx express-generator-typescript
Setting up new Express/TypeScript project...
npm ERR! Unexpected end of JSON input while parsing near '...registry.npmjs.org/ts'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\temet\AppData\Roaming\npm-cache\_logs\2020-06-03T20_52_22_094Z-debug.log
Error: Command failed: npm i -D ts-node tslint typescript nodemon find jasmine supertest @types/node @types/express @types/jasmine @types/find @types/morgan @types/cookie-parser @types/supertest fs-extra tsconfig-paths @types/jsonfile jsonfile @types/command-line-args @types/helmet
npm ERR! Unexpected end of JSON input while parsing near '...registry.npmjs.org/ts'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\temet\AppData\Roaming\npm-cache\_logs\2020-06-03T20_52_22_094Z-debug.log

    at checkExecSyncError (child_process.js:630:11)
    at Object.execSync (child_process.js:666:15)
    at downloadNodeModules (C:\ProgramData\nvm\v12.17.0\node_modules\express-generator-typescript\lib\express-generator-typescript.js:67:18)
    at expressGenTs (C:\ProgramData\nvm\v12.17.0\node_modules\express-generator-typescript\lib\express-generator-typescript.js:18:9) {
  status: 1,
  signal: null,
  output: [
    null,
    <Buffer >,
    <Buffer 6e 70 6d 20 45 52 52 21 20 55 6e 65 78 70 65 63 74 65 64 20 65 6e 64 20 6f 66 20 4a 53 4f 4e 20 69 6e 70 75 74 20 77 68 69 6c 65 20 70 61 72 73 69 6e ... 183 more bytes>
  ],
  pid: 2044,
  stdout: <Buffer >,
  stderr: <Buffer 6e 70 6d 20 45 52 52 21 20 55 6e 65 78 70 65 63 74 65 64 20 65 6e 64 20 6f 66 20 4a 53 4f 4e 20 69 6e 70 75 74 20 77 68 69 6c 65 20 70 61 72 73 69 6e ... 183 more bytes>
}
Project setup complete!

tslint is being deprecated

Hi there, TSLint is being deprecated in favor of ES Lint. Will we be seeing changes soon or can put in a PR?

better not make a project

should not make a project in your generator. A generator should generate a clean state of the framework.

Debugging the application

Hello all,
I am a newbie to node and typescript. I wanted to debug the user APIs. Is there any way to accomplish it? Any hint would be of great help for me.

VSCode: Parsing error at line 1 col 1 of every ts file

I created a new project with:

$ cd projects
$ express-generator-typescript --socket-io "crudn"

and then opened it in Visual Studio Code (Linux). VSCode underlines in red every 1st character of every ts file and complains with:

Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
The file does not match your project config: ../../../../projects/crudn/src/index.ts.
The file must be included in at least one of the projects provided.

What's next?

Production build connection refused

After running npm run build and npm start, the server starts as per your logs in the required port. But the server refuses all connections even in localhost

Property 'id' does not exist on type 'string[]'.

On first time setup I got an error:

TSError: ⨯ Unable to compile TypeScript:
src/routes/Users.ts:77:35 - error TS2339: Property 'id' does not exist on type 'Params'.
  Property 'id' does not exist on type 'string[]'.

77     return console.log(req.params.id);
                                     ~~

    at createTSError (E:\TypeScript\boilerplate\node_modules\ts-node\src\index.ts:245:12)
    at reportTSError (E:\TypeScript\boilerplate\node_modules\ts-node\src\index.ts:249:19)
    at getOutput (E:\TypeScript\boilerplate\node_modules\ts-node\src\index.ts:362:34)
    at Object.compile (E:\TypeScript\boilerplate\node_modules\ts-node\src\index.ts:395:32)
    at Module.m._compile (E:\TypeScript\boilerplate\node_modules\ts-node\src\index.ts:473:43)
    at Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Object.require.extensions.(anonymous function) [as .ts] (E:\TypeScript\boilerplate\node_modules\ts-node\src\index.ts:476:12)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

This was solved after changing:
router.delete('/delete/:id', async (req: Request, res: Response) => {
to
router.delete('/delete/:id', async (req: any, res: Response) => {
But this approach doesn't feels correct.


This is how I solved it for now:

router.delete('/delete/:id', async (req: Request, res: Response) => {
    try {
        const idJSON = req.params;
        const id = idJSON;
        await userDao.delete(Number(id));
        return res.status(OK).end();
    } catch (err) {
        logger.error(err.message, err);
        return res.status(BAD_REQUEST).json({
            error: err.message,
        });
    }
});

ESLint Error, any way around it?

I am fairly new to TypeScript. Using this starter (thanks btw) I receive an error when running eslint

Users/mikee/Documents/code/typescript/express-ts/src/entities/User.ts
  3:3  error  Parsing error: Unexpected token

  1 | interface IUser {
  2 |   name: string
> 3 |   email: string
    |   ^
  4 | }
  5 | 
  6 | class User implements IUser {

 1 problem (1 error, 0 warnings)

When starting a project, I get ESLint errors in VS Code

Promise returned in function argument where a void return was expected.eslint@typescript-eslint/no-misused-promises

in /src/routes/index.ts
on

userRouter.get('/all', getAllUsers);

and on src/index.ts
I get

Unsafe call of an `any` typed value.eslint@typescript-eslint/no-unsafe-call

on app.listen(port, () => {

Running the app

On the Quick Start section it's helpful to add also the commands:
npm install && npm run build after

cd "project name"

error TS2571: Object is of type 'unknown'

I'm running in to this error when starting a project as follow:

npx express-generator-typescript --with-auth "express-ts-auth"

and then when compiling:

node ➜ /workspaces/express-ts-auth $ npm run build

> [email protected] build
> ./node_modules/.bin/ts-node build.ts

INFO: src/routes/middleware.ts(32,20): error TS2571: Object is of type 'unknown'.

ERROR: Error: Command failed: tsc --build tsconfig.prod.json

node ➜ /workspaces/express-ts-auth $ node -v
v16.8.0
node ➜ /workspaces/express-ts-auth $ npm -v
7.21.0
node ➜ /workspaces/express-ts-auth $ 

also when I ran the test I encounter this error:

/workspaces/express-ts-auth/node_modules/ts-node/src/index.ts:692
    return new TSError(diagnosticText, diagnosticCodes);
           ^
TSError: ⨯ Unable to compile TypeScript:
spec/index.ts:20:29 - error TS2345: Argument of type 'null' is not assignable to parameter of type 'JasmineOptions'.

20 const jasmine = new Jasmine(null);

I'm using a container for the compilation.

NODE_OPTIONS='--inspect' not working

Hi based on the issue#13 I added a debug script to my package.json which looks like "start:dev:debug": "nodemon --config nodemon.debug.json ", and my nodemon.debug.json looks like

{
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/public"],
  "inspect": true,
  "exec": "NODE_OPTIONS='--inspect' ts-node -r tsconfig-paths/register ./src --env=development"
}

now when I do npm run start:dev:debug I get the following and debugger doesn't work.

> [email protected] start:dev:debug C:\Development\App101
> nodemon --config nodemon.debug.json

[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): src\**\*
[nodemon] watching extensions: ts
[nodemon] starting `NODE_OPTIONS='--inspect' ts-node -r tsconfig-paths/register ./src --env=development`
'NODE_OPTIONS' is not recognized as an internal or external command,
operable program or batch file.
[nodemon] app crashed - waiting for file changes before starting...

BTW I am using VS Code on Windows 10. Any idea how to make this work...

log transpile (tsc) error

Hello,
the build.js script does not log error during the transpile step.
I tried this with no success :
const proc = childProcess.exec('tsc --build tsconfig.prod.json', (error) => { if (error) console.log('my log : ' + error); });
But the error does not contains any details.

What helped me was to :

  • remove from build.js childProcess.exec('tsc --build tsconfig.prod.json')
  • add to package.json "scripts": { "build": "node ./util/build.js && npm run transpile", "tsc": "tsc --build tsconfig.prod.json", "transpile": "npm run tsc"}

By executing the tsc command this way, errors are logged. It saved me when I was trying to deploy on Heroku, maybe it can help others.

Elise

Contribute to Express

Hi Sean,

I am a member of the Express TC. I have been recently been working on a replacement to the (out of date IMO) express generator. One of the things I wanted before I finalized the documentation on it and moved it over as the official generator was a TS version.

I just happened to see a tweet which had a link to this repo, and it makes much more sense to me to have someone with more expertise in TS than I to write the template. I was wondering if you would be willing to collaborate on an "official" project scaffold?

On a side note, if you are up for helping, we have need of people willing to help us support the typing declarations: expressjs/express#2818

Production build error

I'm trying to run production after the build. But It's not working.

kaushal@kaushal-pc:~/Documents/project$ npm start

> [email protected] start /home/kaushal/Documents/project/
> node -r module-alias/register ./dist

internal/modules/cjs/loader.js:797
    throw err;
    ^

Error: Cannot find module '/home/kaushal/Documents/project/dist'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
    at Function.Module._resolveFilename (/home/kaushal/Documents/project/node_modules/module-alias/index.js:49:29)
    at Function.Module._load (internal/modules/cjs/loader.js:687:27)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node -r module-alias/register ./dist`
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/kaushal/.npm/_logs/2020-04-27T17_00_37_944Z-debug.log

can you help me to solve this problem?

Is there a way to build the application in development mode so that dotenv files are copied to dist/pre-start?

First of all, many thanks for this neat project! :)

I am trying to figure out how to create a script in the package.json file so that when building the application in a local environment the dotenv files in src/pre-start are automatically copied to the respective dist folder.

The reason is that my project has a frontend and a backend part.

The frontend is usually built into the dist/public folder of the express app, and then it is served by the backend.

However, I would like to access different environment variables defined in my development.env file, but I cannot do it right now since the only one present is apparently only production.env.

I guess it is normal behavior, but anyone knows how can I do it? copying manually or inserting a cp command into the package.json scripts?

Thanks in advance.

I can't deploy my app on Azure

Hi.

I have a problem with deploying the app in Azure.

The command: npm run start generates the next error:

2019-09-17T17:32:15.075119582Z > [email protected] start /home/site/wwwroot
2019-09-17T17:32:15.075135283Z > cross-env ENV_FILE=production node -r ./env -r module-alias/register ./dist/start.js
2019-09-17T17:32:15.075140583Z 
2019-09-17T17:32:15.611200168Z internal/modules/cjs/loader.js:583
2019-09-17T17:32:15.611228570Z     throw err;
2019-09-17T17:32:15.611233470Z     ^
2019-09-17T17:32:15.611237070Z 
2019-09-17T17:32:15.611240770Z Error: Cannot find module '..'
2019-09-17T17:32:15.611244570Z     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
2019-09-17T17:32:15.611248670Z     at Function.Module._load (internal/modules/cjs/loader.js:507:25)
2019-09-17T17:32:15.611253171Z     at Module.require (internal/modules/cjs/loader.js:637:17)
2019-09-17T17:32:15.611257071Z     at require (internal/modules/cjs/helpers.js:22:18)
2019-09-17T17:32:15.611260671Z     at Object. (/home/site/wwwroot/node_modules/.bin/cross-env:4:16)
2019-09-17T17:32:15.611264971Z     at Module._compile (internal/modules/cjs/loader.js:689:30)
2019-09-17T17:32:15.611268571Z     at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
2019-09-17T17:32:15.611272271Z     at Module.load (internal/modules/cjs/loader.js:599:32)
2019-09-17T17:32:15.611275871Z     at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
2019-09-17T17:32:15.611279672Z     at Function.Module._load (internal/modules/cjs/loader.js:530:3)
2019-09-17T17:32:15.671881457Z npm ERR! code ELIFECYCLE
2019-09-17T17:32:15.700250121Z npm ERR! errno 1
2019-09-17T17:32:15.708948777Z npm ERR! [email protected] start: `cross-env ENV_FILE=production node -r ./env -r module-alias/register ./dist/start.js`
2019-09-17T17:32:15.709719209Z npm ERR! Exit status 1
2019-09-17T17:32:15.710555543Z npm ERR! 
2019-09-17T17:32:15.711515983Z npm ERR! Failed at the [email protected] start script.
2019-09-17T17:32:15.718314961Z npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2019-09-17T17:32:15.816054370Z 
2019-09-17T17:32:15.817110013Z npm ERR! A complete log of this run can be found in:
2019-09-17T17:32:15.817851744Z npm ERR!     /root/.npm/_logs/2019-09-17T17_32_15_719Z-debug.log

So... I need your help, please!

daos

Just wondering what daos stood for?

Why token generate at client side.

We can see in the following request that token is going from the client-side with login details. why the token is generated on the client-side?? Can anyone explain it ?? It's confusing.

image

npm start not working

hello, thanks for this package.
However, when I try to run it for production using your documentation npm start
i get these errors

[email protected] start /Users/peterschikezie/iCloud Drive (Archive)/Documents/projects/halloween > node -r module-alias/register ./dist

internal/modules/cjs/loader.js:796
throw err;
^
Error: Cannot find module '/Users/peterschikezie/iCloud Drive (Archive)/Documents/projects/halloween/dist'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._resolveFilename (/Users/peterschikezie/iCloud Drive (Archive)/Documents/projects/halloween/node_modules/module-alias/index.js:49:29)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

Is there something i am not doing correctly?
i have Googled and found no help. Please help me out.

Thanks in advance

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.