【TS入门笔记6---快速创建ts项目】

发布于:2025-05-01 ⋅ 阅读:(20) ⋅ 点赞:(0)

TypeScript—快速创建ts项目

一、在 Node.js 中使用 TypeScript

1. 初始化项目

mkdir node-ts-project && cd node-ts-project
npm init -y

2.安装依赖

npm install typescript ts-node @types/node --save-dev

3.配置 tsconfig.json

npx tsc --init

修改生成的 tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "rootDir": "./src",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"]
}

4. 编写示例代码

// src/index.ts
import http from 'http';

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from TypeScript!');
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

5. 运行与调试

直接运行(使用 ts-node):

npx ts-node src/index.ts

编译后运行:

npx tsc && node dist/index.js

二、在浏览器中使用 TypeScript

1. 初始化项目

mkdir browser-ts-project && cd browser-ts-project
npm init -y

2. 安装依赖

npm install typescript webpack webpack-cli webpack-dev-server ts-loader html-webpack-plugin --save-dev

上述配置表示将 src 目录下的所有 .ts 文件纳入编译上下文。

3. 配置文件

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "ESNext",
    "strict": true,
    "lib": ["DOM", "ES6"]
  }
}

webpack.config.js:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  entry: './src/index.ts',
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    new HtmlWebpackPlugin({ template: './src/index.html' })
  ],
  devServer: {
    static: './dist',
  },
};

4. 编写代码

src/index.ts:

document.getElementById('app')!.textContent = 'Hello from TypeScript!';

src/index.html:

<!DOCTYPE html>
<html>
  <body>
    <div id="app"></div>
  </body>
</html>

5. 运行开发服务器

npx webpack serve --open

三、创建可复用的 TypeScript 模块

1. 初始化模块项目

mkdir ts-module && cd ts-module
npm init -y

2. 安装依赖

npm install typescript --save-dev

类型和值声明空间的区别:类型声明空间中的声明只能用于类型相关的操作,而值声明空间中的声明可以在运行时被调用或使用。例如,不能将接口作为值来传递或调用。

3. 配置 tsconfig.json

npx tsc --init

4. 修改配置

{
  "compilerOptions": {
    "target": "ES6",
    "module": "ESNext",
    "declaration": true,  // 生成 .d.ts 类型声明文件
    "outDir": "./dist",
    "strict": true
  },
  "include": ["src/**/*"]
}

5. 编写模块代码

// src/math.ts
export function add(a: number, b: number): number {
  return a + b;
}

export function multiply(a: number, b: number): number {
  return a * b;
}

6. 配置 package.json

{
  "name": "ts-math-module",
  "version": "1.0.0",
  "main": "dist/math.js",       // 编译后的入口文件
  "types": "dist/math.d.ts",    // 类型声明文件
  "scripts": {
    "build": "tsc",
    "prepublish": "npm run build"
  }
}

7. 构建与发布

(1)本地构建

npm run build

(2)本地测试
在其他项目中运行 npm link ts-math-module 即可使用

npm link

(3)发布到 npm

npm publish

四、关键总结

TS


网站公告

今日签到

点亮在社区的每一天
去签到