Application scenarios

In code daily, often need to write a variety of scripts, today I use TS to write a script, running a variety of errors, or decided to write down.

A ts-Node library is required to run the TS script. This library cannot be installed globally or an error will be reported.

Yarn add -d ts-node # or NPM I ts-node -dCopy the code

use

Start adding configuration items after installation:

  • ints.config.jsonAdd configuration to"mudoule": esnextores2005
  • inpackage.jsonAdd configuration to"type":"modules"
  • In the fileimportIn the statementContains the file extension, such asimport data from './data'Instead ofimport data from './data.js'And the other.tsThe suffix should also be changed.js

You can then run the TS script using command-line commands.

node --loader ts-node/esm ./my-script.ts
Copy the code

An error

In this process, many mistakes were reported, running around in various online forums, and finally solved the problem.

SyntaxError: Cannot use import statement outside a module

There is no way to use import outside of a module. To fix this, add “type”:”modules” to the package.json file.

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\1\Desktop\my-project\data' imported from 'C:\Users\1\Desktop\get-data.ts'

The imported module could not be found because no suffix was added to the imported file.

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

When I received this error, the command line was using ts-node./myscripts.ts.

node --loader ts-node/esm ./my-script.ts
Copy the code

ReferenceError: fetch is not defined

Fetching data uses the FETCH library, not the standard Nodejs method, and requires downloading Node-FETCH

yarn add node-fetch
Copy the code

Write in the last

While there are a number of community forums where programmers can communicate their Issues, a quick run through github’s Issues is still a faster and more effective way to search for questions, and a lot of invalid or even wrong answers are found elsewhere.