The Express Generator provides a nice scaffold, but it doesn’t produce many files. It doesn’t have an option for avoiding any view templating languages, which is unfortunate, but easy enough to work around. If we ignore the directories and the view templating engines, the generator only produces 6 files.
Great place to start then!
Things that are not impacted by TypeScript
There’s nothing to change here. The style.css can stay exactly the same as in the generator.
views/index.ejs –> public/index.html
Avoiding a template engine means we’re going to have to serve up something different. A static file will work fine, so we’ll swap out index.ejs for the equivalent static HTML file and throw it in the public folder – `public/index.html’.
views/error.ejs –> public/error.html
Same goes for the Error view, but unfortunately we lose some functionality here – as the file is static we can’t dynamically add the error. Works for now! public/error.html:
Things we need to add
This is unfortunate, but in the generated app.js there are these two lines when catching 404 errors:
Error doesn’t have a status, so this will blow up for us as soon as we add some typing information. We can add a wrapper in its place models/http_error.ts that we’ll use when we look at converting the app.js file. We could also get rid of the status entirely, as we’re not rendering it anymore.
The fun stuff
This is where we get into the mess of TypeScript. First of all, we can use everything that the generator produced (except of course we’ll get rid of the ejs dependency):
Then we add the TypeScript specific things:
1. The big one – TypeScript itself:
2. Add the types for Node:
3. Create our tsconfig.json file
And this pushes us off the edge of the cliff.
"module" can be: None, CommonJS, AMD, System, UMD, ES6, or ES2015
"target" can be: ES3, ES5, ES6/ES2015, ES2016, ES2017 or ESNext
Now we’ve committed to set up Babel as well…
4. Add all the remaining relevant typing dependencies in one big shot
This stays pretty much the same as it is in the generator. The difference here is that the view engine has been swapped for a static file. Additionally, to make it easier to serve up the static file this makes use of global variable – the path to the root of the server.
Same story here, pretty much the same as it is in the generator.
This is a big one in terms of changing the structure. It quite naturally looks like it should be a class in the general vicinity of App. This is different than the structure of app.js, but it seems different in a positive way. There are a couple other changes here:
swapped out the view engine for static files, removing the view engine lines
added in the HttpError in place of the Error object
Check out another take on the subject here – what I read before starting. Also, remember you can find the code for this project here.