

介绍了如何初始化 npm 项目并安装 TypeScript,通过 tsconfig.json 配置和 tsc 编译 .ts 文件。使用 webpack 和 ts-loader 实现打包,并通过 ESLint 配置代码规范检测与修复。详细说明了各步骤的依赖安装、配置文件创建及命令运行。
npm:
npm initGit:
git initnpm i typescript -D查看版本:
npx tsc --versiontsconfig.jsonnpx tsc --init.ts新建 index.ts 文件。
项目目录:
├── package.json
├── tsconfig.json
└── src
└── index.ts文件 index.ts:
const ProjectName = "new-typescript-project";
function say(): string {
return `This project is ${ProjectName}.`;
}
console.log(say());编译:
npx tsc src/index.ts --outDir dist结果:
var ProjectName = "new-typescript-project";
function say() {
return "This project is ".concat(ProjectName, ".");
}
console.log(say());监听文件变化:
npx tsc --watch src/index.ts --outDir distnpm install webpack webpack-cli -Dts-loadernpm install ts-loader -Dwebpack.config.jsconst path = require('path');
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module:{
rules:[
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.ts', '.tsx']
}
};npx webpack --config webpack.config.js结果:
(()=>{"use strict";console.log("This project is new-typescript-project.")})();npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-prettier -Deslint.config.cjstouch eslint.config.cjsconst tsPlugin = require('@typescript-eslint/eslint-plugin');
const tsParser = require('@typescript-eslint/parser');
const prettierPlugin = require('eslint-plugin-prettier');
const tsRecommendedRules =
tsPlugin && tsPlugin.configs && tsPlugin.configs.recommended
? tsPlugin.configs.recommended.rules
: {};
module.exports = [
{
ignores: ['node_modules/**', 'dist/**', 'build/**', '*.min.js', '.git/**']
},
{
files: ['**/*.ts', '**/*.tsx'],
languageOptions: {
parser: tsParser,
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname
}
},
plugins: {
'@typescript-eslint': tsPlugin,
prettier: prettierPlugin
},
rules: {
...tsRecommendedRules,
'prettier/prettier': 'error',
'no-console': 'off',
'@typescript-eslint/no-inferrable-types': 'off'
}
},
{
files: ['**/*.js', '**/*.jsx'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {
'no-unused-vars': 'warn'
}
}
];package.json 中添加检测脚本"lint": "eslint src/index.ts --ext .ts"npm run lint报错示例:
const ProjectName = "new-typescript-project"1:45 error Insert `;` prettier/prettier修改相应代码:
- const ProjectName = "new-typescript-project"
+ const ProjectName = "new-typescript-project";再次运行通过!
脚本添加 --fix 选项:
"lint:fix": "eslint src/index.ts --ext .ts --fix""lint:fix": "eslint src/index.ts --ext .ts,.tsx --fix"案例: GitHub: new-typescript-project
本文章首次编辑于 2020-08-18,最近更新于 2025-10-27。项目代码在 Node.js 16.x 上已测试可稳定运行。
版权声明
本文为原创文章,作者保留版权。转载请保留本文完整内容,并以超链接形式注明作者及原文出处。
作者: 除除
原文: http://blog.mazey.net/1685.html
(完)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。