TypeScript Boilerplate 项目教程
1. 项目目录结构及介绍
typescript-boilerplate/
├── src/
│ ├── main.ts
│ └── ...
├── .editorconfig
├── .eslintrc.js
├── .gitignore
├── .gitlab-ci.yml
├── .npmignore
├── LICENSE
├── README.md
├── browser-test.html
├── jest.config.js
├── package.json
├── tsconfig.json
└── yarn.lock
目录结构介绍
- src/: 存放项目的主要源代码文件。
- main.ts: 项目的入口文件。
- .editorconfig: 配置文件,用于统一不同编辑器和IDE的代码风格。
- .eslintrc.js: ESLint 配置文件,用于代码风格检查和错误检测。
- .gitignore: Git 忽略文件配置,指定哪些文件和目录不需要被版本控制。
- .gitlab-ci.yml: GitLab CI 配置文件,用于持续集成。
- .npmignore: npm 忽略文件配置,指定哪些文件和目录不需要被发布到 npm。
- LICENSE: 项目的开源许可证文件。
- README.md: 项目的说明文档。
- browser-test.html: 用于浏览器测试的 HTML 文件。
- jest.config.js: Jest 测试框架的配置文件。
- package.json: 项目的 npm 配置文件,包含项目的依赖、脚本等信息。
- tsconfig.json: TypeScript 编译器的配置文件。
- yarn.lock: Yarn 包管理器的锁定文件,确保依赖版本一致性。
2. 项目启动文件介绍
src/main.ts
main.ts
是项目的入口文件,负责初始化项目并启动应用。以下是一个简单的示例:
// src/main.ts
import { greet } from './greet';
console.log(greet('World'));
启动命令
在 package.json
中,你可以找到启动项目的命令:
{
"scripts": {
"start": "node dist/main.js",
"build": "tsc",
"test": "jest"
}
}
npm start
: 启动项目。npm run build
: 编译 TypeScript 代码。npm test
: 运行测试。
3. 项目配置文件介绍
tsconfig.json
tsconfig.json
是 TypeScript 编译器的配置文件,定义了编译选项和项目结构。以下是一个示例配置:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
.eslintrc.js
.eslintrc.js
是 ESLint 的配置文件,用于代码风格检查和错误检测。以下是一个示例配置:
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
// 自定义规则
}
};
jest.config.js
jest.config.js
是 Jest 测试框架的配置文件,定义了测试环境、测试文件匹配规则等。以下是一个示例配置:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/*.spec.ts'],
collectCoverage: true,
coverageDirectory: 'coverage',
coverageReporters: ['text', 'lcov'],
};
通过以上配置,你可以快速启动和配置 TypeScript 项目,并进行代码风格检查和单元测试。