编辑器支持
- VSCode - Vue官方强烈推荐,为TypeScript提供了开箱即用的支持,可以搭配 Vetur 插件 、prettier 插件、ESLint 插件使用
- WebStorm - 同样提供了对TypeScript的开箱即用的支持
工程创建 - Vue Cli
官方推荐使用 Vue Cli 创建 Vue TypeScript 工程。推荐选择ts+eslint+prettier组合,选项配置如下:
插件选择
必选:Babel、TypeScript、Linter / Formatter
各项配置
Use class-style component syntax?
是否使用 vue-class-component 写法?选择 yes
Use Babel alongside TypeScript for auto-detected polyfills?
Pick a linter / formatter config:
选择代码格式规范及格式化配置:选择 ESLint + Prettier
Pick additional lint features:
选择lint方式:选择 Lint on save ,保存时格式化
Where do you prefer placing config for Babel, PostCSS, ESLint, etc.?
选择Babel、ESLint等工具的配置存放的位置?选择 In dedicated config files ,在各自的配置文件中。
npm包推荐
- vue-property-decorator - 使用ts+装饰器+类语法开发Vue项目的基础,它强依赖于Vue官方推出的vue-class-component库。
- vuex-module-decorators - 本文档中使用该库来进行Vuex的TypeScript化,主要是以装饰器+模块化的方式使用Vuex,可以参考Vuex官方文档着重学习modules和模块动态注册。当然不学也行,本文档中展示的Vuex用法非常的简单易懂。
项目配置推荐
Vue工程配置 - vue.config.js
这一步主要是为了适配 vuex-module-decorators 模块的配置。
// vue.config.jsmodule.exports = {// ... your other optionstranspileDependencies: ['vuex-module-decorators'],}
TypeScript编译选项 - tsconfig.json
{"compilerOptions": {// 指定编译之后的版本目录"target": "esnext",// 指定要使用的模板标准"module": "esnext",// 用于指定是否启动所有类型检查"strict": true,// 设置解析非相对模块名称的基本目录"baseUrl": ".",// allowJs用来指定是否允许编译JS文件,默认false,即不编译JS文件"allowJs": true,// 指定jsx代码用于的开发环境:'preserve','react-native',or 'react"jsx": "preserve",// 指定是否引入tslib里的复制工具函数"importHelpers": true,// 模块解析策略,有"node"和"classic"两种类型"moduleResolution": "node",// 是否启用实验性的装饰器特性"experimentalDecorators": true,// 是否跳过所有声明文件的类型检查"skipLibCheck": false,// 通过导入内容创建命名空间,实现CommonJS和ES模块之间的互操作性"esModuleInterop": true,// 允许从没有默认导出的模块中默认导入"allowSyntheticDefaultImports": true,// 检测是否在函数中没有使用的参数"noUnusedParameters": true,// socuceMap用来指定编译时是否生成.map文件"sourceMap": true,// 指定需要包含的模块,只有在这里列出的模块的声明文件才会被加载"types": ["webpack-env"],// 设置模块名到基于baseUrl的路径映射,可以设置路径别名的语法提示"paths": {"@/*": ["src/*"]},// lib用于指定要包含在编译中的库文件"lib": ["esnext", "dom", "dom.iterable", "scripthost"]},// 指定待编译的文件"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],// 指定不编译的文件"exclude": ["node_modules"]}
代码编译 - babel.config.js
module.exports = {presets: ["@vue/cli-plugin-babel/preset"]};
代码检查 - .eslintrc.js
module.exports = {// 预置规则,推荐使用vue提供的规则extends: ['plugin:vue/recommended', '@vue/typescript/recommended'],// 使用typescript解析器parserOptions: {parser: '@typescript-eslint/parser',ecmaVersion: 2020,sourceType: 'module',},plugins: ['@typescript-eslint'],rules: {// override/add rules settings here, such as:// 是否禁止非空断言'@typescript-eslint/no-non-null-assertion': ['off'],// 是否禁止非必要且多余的类型声明'@typescript-eslint/no-inferrable-types': ['off'],// 是否禁止require()'@typescript-eslint/no-var-requires': ['off'],// interface声明每行是否必须加分号'@typescript-eslint/member-delimiter-style': ['off'],// 是否禁止any类型'@typescript-eslint/no-explicit-any': ['warn'],// 是否禁止空函数出现'@typescript-eslint/no-empty-function': ['warn'],// 是否禁止this赋值别名,仅允许 解构赋值 和 变量名self'@typescript-eslint/no-this-alias': ['error',{allowDestructuring: true, // Allow `const { props, state } = this`; false by defaultallowedNames: ['self', 'that'], // Allow `const self = this`; `const that = this`; `[]` by default},],},}
代码格式化配置 - .prettierrc.js
module.exports = {printWidth: 100, // 超过最大值换行tabWidth: 2, // 缩进字节数useTabs: false, // 缩进不使用tab,使用空格semi: false, // 句尾添加分号singleQuote: true, // 使用单引号代替双引号arrowParens: 'avoid', // (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号bracketSpacing: true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"disableLanguages: ['vue'], // 不格式化vue文件,vue文件的格式化单独设置endOfLine: 'auto', // 结尾是 \n \r \n\r autotrailingComma: 'es5', // 多行时尽可能打印尾随逗号<none|es5|all>jsxBracketSameLine: true,htmlWhitespaceSensitivity: 'css', // 指定HTML文件的全局空格敏感度 <css|strict|ignore>}
编辑器(VS Code)配置 - .vscode/setting.json
{"[vue]": {"editor.defaultFormatter": "octref.vetur"},"vetur.validation.template": false,"vetur.format.defaultFormatter.html": "js-beautify-html","vetur.format.options.tabSize": 2,"vetur.format.defaultFormatterOptions": {"js-beautify-html": {// 属性强制折行对齐"wrap_attributes": "force-expand-multiline"},// .vue prettier配置"prettier": {"printWidth": 100, // 超过最大值换行"tabWidth": 2, // 缩进字节数"useTabs": false, // 缩进不使用tab,使用空格"semi": false, // 句尾添加分号"singleQuote": true, // 使用单引号代替双引号"arrowParens": "avoid", // (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号"bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }""endOfLine": "auto", // 结尾是 \n \r \n\r auto"trailingComma": "es5", // 多行时尽可能打印尾随逗号<none|es5|all>"jsxBracketSameLine": true,"htmlWhitespaceSensitivity": "css", // 指定HTML文件的全局空格敏感度 <css|strict|ignore>}},}
项目结构
├── .vscode│ └── setting.json # 编辑器设置配置文件,也可以直接配置在个人编辑器中├── public├── src│ ├── api # 接口api│ ├── assets # 图片、样式等│ ├── components # Vue 组件│ ├── constant # 常量文件夹│ ├── mock # mock数据│ ├── router # Vue Router│ ├── store # Vuex│ ├── typings # 全局声明文件夹│ │ ├── shims-tsx.d.ts # Vue 支持jsx写法的声明│ │ └── shims-vue.d.ts # Vue 支持.vue文件类型检查的声明│ ├── utils # 工具函数│ ├── views # Vue 视图│ ├── App.vue # Vue 主入口视图│ └── main.ts # Vue 主入口文件├── .browserslistrc├── .eslintrc # ESLint 配置文件├── .prettierrc.js # prettier 格式化配置文件├── babel.config.js # Babel 配置文件├── package.json├── tsconfig.json # TypeScript 编译配置└── vue.config.js # Vue 工程配置
