vue项目引入ts步骤(小结)

2020-06-12 20:47:27易采站长站整理

最近考虑到老项目代码的可维护性以及稳定性,决定引入ts做规范检测。因为介绍的东西比较基础,如果介绍的不对,麻烦指正。

1. 简介

TypeScript 是 JavaScript 的一个超集,主要提供了类型系统和对 ES6 的支持。网上关于ts的学习资料很多,这里不做详细介绍。可参考的学习网站:

ts.xcatliu.com/

typescript.bootcss.com/

2. 安装依赖包


cnpm i typescript ts-loader --save-dev

3. 添加tsconfig.json文件

在项目根目录下添加 tsconfig.json 文件。tsconfig.json 文件用来指定ts的编译选项。配置可参考:

https://typescript.bootcss.com/tsconfig-json.html

项目工程 tsconfig.json 文件配置如下:(仅做参考)


{
"compilerOptions": {
"baseUrl": ".",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmitOnError": true,
"target": "esnext",
"module": "esnext",
"strict": true,
"allowJs": true,
"noEmit": false,
"noImplicitThis": true,
"esModuleInterop": true,
"sourceMap": true,
"moduleResolution": "node"
},
"include": [
"src/**/*", "types"
],
"exclude": [
"node_modules",
"build"
]}

4. webpack打包配置修改

webpack.config.js 打包文件修改,新增对.ts文件的打包配置。

4.1 入口文件后缀名由.js修改为.ts


module.exports = {
entry: {
app: ['@babel/polyfill', './src/main.ts'] }
}

4.2 extensions 文件扩展名增加 .ts, .tsx 文件的支持

tsx针对react项目文件的支持,因为我们的工程基于vue开发,支持.ts文件就可以了。


module.exports = {
resolve: {
extensions: ['.js', '.vue', '.json', '.css', '.ts'] }
}

4.3 loader增加对ts文件的支持

使用ts-loader来转换ts文件。


module.exports = {
module: {
rules: [
{
test: /.ts?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/.vue$/],
}
}
] }
}

5. eslint 添加对ts文件的检测

5.1 安装依赖包


cnpm i @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-typescript eslint-plugin-typescript --save-dev

@typescript-eslint/parser ts文件解析器

@typescript-eslint/eslint-plugin 版本号需要与@typescript-eslint/parser的版本一致,解析器相关的配置选项