0%

run-typescript-with-node

Firstly, node can’t run typescript files directly. You need to compile the typescript files to javascript files and then run them with node.

The following command won’t work!

1
node ./src/main.ts

You’ll got error like this:

1
2
3
(node:13596) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

SyntaxError: Cannot use import statement outside a module

How to solve this problem?

  1. Use ts-node to run typescript files directly.
    1. npm install -g ts-node
    2. ts-node ./src/main.ts
  2. Use tsc to compile typescript files to javascript files and then run them with node.
    1. npm install -g typescript
    2. tsc ./src/main.ts
    3. node ./src/main.js

Happy coding!