乐闻世界logo
搜索文章和话题

How to compile typescript using npm command?

1个答案

1

When compiling TypeScript code with npm, typically follow these steps:

1. Initialize the npm Project

First, ensure your project has a package.json file. If not present, you can create it by running the following command:

bash
npm init -y

This command creates a default package.json file.

2. Install TypeScript

Next, install the TypeScript compiler using npm as a dev dependency:

bash
npm install typescript --save-dev

This command adds the TypeScript compiler to your project's dev dependencies and updates the package.json file.

3. Configure TypeScript

After installing TypeScript, create a configuration file tsconfig.json that specifies the compiler options. You can manually create this file or generate it using the TypeScript CLI:

bash
npx tsc --init

This command creates a pre-configured tsconfig.json file. You can modify the compiler options as needed, such as target (specifying the ECMAScript target version), module (specifying the module system), and outDir (specifying the output directory).

4. Write TypeScript Code

Create a .ts file in your project and write TypeScript code. For example, create a src/index.ts file:

typescript
function greet(name: string): string { return `Hello, ${name}!`; } console.log(greet("World"));

5. Compile TypeScript Code

With the configuration file and TypeScript source code in place, compile the code by running the TypeScript compiler. Add an npm script to package.json for quick execution of the compilation command:

json
"scripts": { "build": "tsc" }

Then, compile the project by running the following command:

bash
npm run build

This will compile the TypeScript code to the specified output directory based on the settings in tsconfig.json.

6. Run the Generated JavaScript Code

After compilation, if your tsconfig.json is correctly configured and outDir is set to dist, you can find the compiled JavaScript files in the dist directory. Run these files:

bash
node dist/index.js

This will output Hello, World! to the console.

Conclusion

By following these steps, you can compile and run TypeScript code using npm and the TypeScript compiler. These steps cover the complete workflow from project initialization to code execution, ensuring effective compilation and execution of TypeScript.

2024年6月29日 12:07 回复

你的答案