lpar / hello-express

An example legacy-free Node.js, Express, TypeScript legacy-free (ES6 modules) hello world project

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

hello-express

An example legacy-free Node.js, Express, TypeScript legacy-free hello world project with ES6 modules, explicitly typed parameters in callbacks, and Jest for unit tests.

Works with Node v12.16.3 and up.

What is this?

This is a version of an Express framework "Hello world" example updated to:

Start via yarn run server. Run tests via yarn test.

Also included are some IntelliJ IDEA configs so you can push a button to run.

Notes

Here are the key "tricks", some of which are still poorly or inaccurately documented on the web:

  1. You need to put "type": "module" in package.json to allow standard module imports in Node.js, as of Node 12.x.
  2. Even after doing that, you still need to use the --experimental-modules command line flag to enable ESM on LTS versions of Node (e.g. 12.x), so that your application's main compiled code can be loaded in module mode.
  3. ...and --experimental-specifier-resolution=node even with Node 14, if you want to load modules within your application without having to specify the filename extension or rename js files to mjs. (The standard doesn't seem to specify whether module names should include the extension or not, so either behavior is allowed.)
  4. You need to enable ES6+ modules in TypeScript by setting "module": "es6" in tsconfig.json.
  5. After doing that, the default module resolution for TypeScript is "classic" so you have to set "moduleResolution": "Node" in tsconfig.json as well.
  6. Since Express isn't packaged as an ES6 module yet, you need to set "allowSyntheticDefaultImports": true in tsconfig.json so you can import the main express function.
  7. Don't follow instructions and run yarn ts-jest config:init, because that seems to generate a config that doesn't run Node properly. Instead, put the Jest config in package.json.

If you skip #2 above, you'll get an error like this:

internal/modules/cjs/loader.js:1174
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /path/to/generated/javascript/main.js

At the time of writing, Yarn complains all the time about the license field in the package.json file. This seems to be a Yarn bug.

About

An example legacy-free Node.js, Express, TypeScript legacy-free (ES6 modules) hello world project


Languages

Language:TypeScript 86.1%Language:Handlebars 13.9%