📜  tsc 节点 - Javascript (1)

📅  最后修改于: 2023-12-03 15:35:22.782000             🧑  作者: Mango

TypeScript Compiler (TSC) Node

TypeScript is an open-source programming language developed by Microsoft. TypeScript is a strict syntactical superset of JavaScript and adds optional static typing to the language. The TypeScript compiler (TSC) is a tool that converts TypeScript files (.ts) into JavaScript files (.js) that can be executed by a browser or node.js.

Installing TSC

To install TSC, you can use either npm (Node Package Manager) or yarn. If you have Node.js installed, you already have npm installed. Yarn is an alternative to npm that is faster and more reliable.

To install TSC with npm, run the following command:

npm install -g typescript

To install TSC with yarn, run the following command:

yarn global add typescript
Using TSC

To use TSC, you need to create a TypeScript file with the .ts extension. For example, create a file called hello.ts with the following code:

function sayHello(name: string) {
  console.log("Hello, " + name);
}

const myName = "John";
sayHello(myName);

To compile the TypeScript file into a JavaScript file, run the following command:

tsc hello.ts

This will create a file called hello.js with the following code:

function sayHello(name) {
  console.log("Hello, " + name);
}
var myName = "John";
sayHello(myName);

Now, you can execute the hello.js file using node.js.

node hello.js

This will output:

Hello, John
Configuring TSC

You can configure TSC using a tsconfig.json file. This file specifies the root files and the compiler options required to compile a TypeScript project. You can create a tsconfig.json file in the root directory of your project and specify the required options.

Here is an example tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "*": [
        "node_modules/*",
        "src/types/*"
      ]
    }
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}
Conclusion

TSC is a powerful tool that makes it easy to develop and maintain TypeScript projects. With TSC, you can easily convert TypeScript files to JavaScript files that can be executed by a browser or node.js. TSC also provides many options that can be used to configure the compiler to suit your needs.