1.搭建项目
1.安装vite
npm i -g create-vite-app
2.创建vite项目
create-vite-app vue3-demo
3.安装依赖
npm install
4.运行项目
npm run dev
2.配置TS环境
使用vite系统定制开发搭建好的项目是没有使用的,系统定制开发所以我们要去安装typescript系统定制开发并修改代码,系统定制开发以保证我们后续可以使用typescript
- 1.安装TS
npm install typescript
- 2.在项目的根目录创建文件:tsconfig.json
// 指定了用来编译这个项目的根文件和编译选项{ "compilerOptions": { "target": "esnext", "module": "esnext", "strict": true, //这样可以对`this`上的数据属性进行严格的推断,否则总是被视为any类型 "jsx": "preserve", "moduleResolution": "node" }, "include": [ "src/**/*", "src/main.d.ts" //**/递归匹配任意子目录 ], "exclude": [ "node_modules" ]}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 3.在项目根目录下新建vite.config.ts
// vite.config.tsimport AutoImport from 'unplugin-auto-import/vite'import Components from 'unplugin-vue-components/vite'import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'export default { plugins: [ // ... AutoImport({ resolvers: [ElementPlusResolver()], }), Components({ resolvers: [ElementPlusResolver()], }), ],}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 3.修改src/main.js为src/main.ts;
- 4.修改根目录下index.html中引入的main.js为main.ts
- 5.修改项目的入口文件为main.ts,在项目根目录创建文件vue.config.js:
module.exports = { pages: { index: { entry: 'src/main.ts' } }};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
注意:经过以上步骤之后,会发现项目还是可以正常启动的,但是在main.ts中会发现有一个报错:
此时是因为使用ts的时候引入.vue文件的时候会报错,找不到相应的模块,是因为ts只认识以.ts结尾的文件,并不认识.vue结尾的文件,以此要在项目的/src
文件下创建一个name.d.ts
文件来定义一下.vue文件:
- 6.src/vue.d.ts
// 在没用用到需要具体定义的内容的时候,可以只声明一下'*.vue'就可以// declare module '*.vue' {// import Vue from 'vue'// export default Vue// }declare module '*.vue' { import { App, defineComponent } from 'vue' const component: ReturnType<typeof defineComponent> & { install(app: App): void } export default component}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 7.src/main.d.ts
// shims-vue.d.tsimport Vue from 'vue'declare module 'vue/types/vue' { interface Vue { // 以下是在main.ts中挂载到Vue.prototype上的变量 $api: any; $mock: any; $configs: any; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
3.安装ESlint
npm install eslint elsint-plugin-vue -D
安装好之后在项目根目录下添加vue.eslintrc.js
文件:
module.exports = { root: true, env: { 'browser': true, 'es2021': true, 'node': true }, extends: [ 'plugin:vue/vue3-essential' ], parserOptions: { 'parser': '@typescript-eslint/parser' }, plugins: [ 'vue', '@typescript-eslint' ], rules: { // 规则可以根据自己项目需求配置 // 各个规则配置含义参考http://eslint.cn/docs/rules/ 'array-bracket-spacing': ['error', 'never'], // 数组紧贴括号部分不允许包含空格 'object-curly-spacing': ['error', 'never'], // 对象紧贴花括号部分不允许包含空格 'block-spacing': ['error', 'never'], // 单行代码块中紧贴括号部分不允许包含空格 'no-multiple-empty-lines': 'error', // 不允许多个空行 }};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26