Typescript project setup (first time)

339 views Asked by At

First off, I didn't see a clear answer after hours of googling, sorry if I overlooked something.

Quick version With Typescript how can I move node_modules to outDir or am I going about things the wrong way?

Long version I'm trying to get started with typescript and configuring the project seems to be the hardest part. My goal is to have my source code in src/server and my output to be in bin/server

Here is my tsconfig.json for reference:

{
    "compilerOptions": {
        "allowJs": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "noEmitOnError": true,
        "noImplicitAny": false,
        "outDir": "../../bin",
        "sourceMap": true,
        "suppressImplicitAnyIndexErrors": true,
        "target": "ES2015",
        "typeRoots": [
        "../../node_modules/@types/"
        ]
    },
    "exclude": [
        "bin/*",
        "node_modules/*",
        "public/*",
        "**/*-aot.ts"
    ]
}

Here is the directory structure:

Project
+-/bin
|  +/server
|     +-server.js
+-/src
  +/server
    +-server.ts
    +-package.json
    +-/node_modules
       +-[...]
    +-/typings
       +-[...]

To compile from ~/Project I use tsc -p src/server, boom we have bin/server/server.js.

To run I am using vs code, here is launch.json:

{
    "version": "0.2.0",
    "configurations": [{
        "outFiles": [ "${workspaceRoot}/bin/server/**/*.js" ],
        "cwd": "${workspaceRoot}/bin/server",
        "name": "Launch",
        "type": "node",
        "request": "launch",
        "program": "${workspaceRoot}/src/server/server.ts",
        "sourceMaps": true,
        "env": {
            "NODE_ENV": "development",
            "SERVER": "http://localhost:8080"
        }
    }]
}

The error I am getting is Error: Cannot find module 'express', the module is installed in src/server/node_modules/express so I'm guessing I have to move node_modules to bin/server as well? That doesn't seem right.

Super new to typescript (started today) thanks for taking the time to read my long post.

PS: Assume everything is on version latest.

1

There are 1 answers

1
Steven Bayer On

Answer found!

I moved tsconfig.json to src/server/ and ran tsc -p src/server from the project root.

Updated tsconfig.json for reference:

{
    "compilerOptions": {
        "allowJs": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "noEmitOnError": true,
        "noImplicitAny": false,
        "outDir": "../../bin",
        "sourceMap": true,
        "suppressImplicitAnyIndexErrors": true,
        "target": "ES2015",
        "typeRoots": ["node_modules/@types/"]
    },
    "exclude": [
        "bin/*",
        "node_modules/*",
        "public/*",
        "**/*-aot.ts"
    ]
}