Vue3 全家桶 + Element Plus + Vite + TypeScript + Eslint 项目配置最佳实践

简介: Vue3 全家桶 + Element Plus + Vite + TypeScript + Eslint 项目配置最佳实践

1. 初化化项目


全局安装 vite-app


npm i -g vite-app

创建项目


yarn create vite-app <project-name>
# 或者
npm init vite-app <project-name>


进入项目,安装依赖

cd <project-name>
yarn # 或 npm i


运行项目


yarn dev


打开浏览器 http://localhost:3000 查看


2. 引入TypeScript


加入 ts 依赖


yarn add --dev typescript


在 项目根目录下创建 TypeScript 的配置文件 tsconfig.json

{
  "compilerOptions": {
    // 允许从没有设置默认导出的模块中默认导入。这并不影响代码的输出,仅为了类型检查。
    "allowSyntheticDefaultImports": true,
    // 解析非相对模块名的基准目录
    "baseUrl": ".",
    "esModuleInterop": true,
    // 从 tslib 导入辅助工具函数(比如 __extends, __rest等)
    "importHelpers": true,
    // 指定生成哪个模块系统代码
    "module": "esnext",
    // 决定如何处理模块。
    "moduleResolution": "node",
    // 启用所有严格类型检查选项。
    // 启用 --strict相当于启用 --noImplicitAny, --noImplicitThis, --alwaysStrict, 
    // --strictNullChecks和 --strictFunctionTypes和--strictPropertyInitialization。
    "strict": true,
    // 生成相应的 .map文件。
    "sourceMap": true,
    // 忽略所有的声明文件( *.d.ts)的类型检查。
    "skipLibCheck": true,
    // 指定ECMAScript目标版本 
    "target": "esnext",
    // 要包含的类型声明文件名列表
    "types": [
    ],
    "isolatedModules": true,
    // 模块名到基于 baseUrl的路径映射的列表。
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    // 编译过程中需要引入的库文件的列表。
    "lib": [
      "ESNext",
      "DOM",
      "DOM.Iterable",
      "ScriptHost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}


在 src 目录下新加 shim.d.ts 文件


/* eslint-disable */
import type { DefineComponent } from 'vue'
declare module '*.vue' {
  const component: DefineComponent<{}, {}, any>
  export default component
}


把 main.js 修改成 main.ts


在根目录,打开 Index.html


<script type="module" src="/src/main.js"></script>
修改为:
<script type="module" src="/src/main.ts"></script>


3. 引入 eslint


安装 eslint prettier 依赖


@typescript-eslint/parser @typescr ipt-eslint/eslint-plugin 为 eslint 对 typescript 支持。


yarn add --dev eslint prettier eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue @typescript-eslint/parser @typescr ipt-eslint/eslint-plugin


在根目录下建立 eslint 配置文件: .eslintrc.js


module.exports = {
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 2020,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier/@typescript-eslint',
    'plugin:prettier/recommended'
  ],
  rules: {
    '@typescript-eslint/ban-ts-ignore': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/no-empty-function': 'off',
    'vue/custom-event-name-casing': 'off',
    'no-use-before-define': 'off',
    // 'no-use-before-define': [
    //   'error',
    //   {
    //     functions: false,
    //     classes: true,
    //   },
    // ],
    '@typescript-eslint/no-use-before-define': 'off',
    // '@typescript-eslint/no-use-before-define': [
    //   'error',
    //   {
    //     functions: false,
    //     classes: true,
    //   },
    // ],
    '@typescript-eslint/ban-ts-comment': 'off',
    '@typescript-eslint/ban-types': 'off',
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^h$',
        varsIgnorePattern: '^h$'
      }
    ],
    'no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^h$',
        varsIgnorePattern: '^h$'
      }
    ],
    'space-before-function-paren': 'off',
    quotes: ['error', 'single'],
    'comma-dangle': ['error', 'never']
  }
};

建立 prettier.config.js


module.exports = {
  printWidth: 100,
  tabWidth: 2,
  useTabs: false,
  semi: false, // 未尾逗号
  vueIndentScriptAndStyle: true,
  singleQuote: true, // 单引号
  quoteProps: 'as-needed',
  bracketSpacing: true,
  trailingComma: 'none', // 未尾分号
  jsxBracketSameLine: false,
  jsxSingleQuote: false,
  arrowParens: 'always',
  insertPragma: false,
  requirePragma: false,
  proseWrap: 'never',
  htmlWhitespaceSensitivity: 'strict',
  endOfLine: 'lf'
}


4. vue-router、vuex


yarn add vue-router@next vuex@next

4.1 vuex


在根目录下创建 store/index.ts


import { InjectionKey } from 'vue'
import { createStore, Store } from 'vuex'
export interface State {
  count: number
}
export const key: InjectionKey<Store<State>> = Symbol()
export const store = createStore<State>({
  state() {
    return {
      count: 0
    }
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})


main.ts 修改


import { createApp } from 'vue'
import { store, key } from './store'
import App from './App'
import './index.css'
const app = createApp(App)
app.use(store, key)
app.mount('#app')


components/HelloWord.vue 修改


<template>
  <h1>{{ msg }}</h1>
  <button @click="inCrement"> count is: </button>
  <p>{{ count }}</p>
</template>
<script>
  import { defineComponent, computed } from 'vue'
  import { useStore } from 'vuex'
  import { key } from '../store'
  export default defineComponent({
    name: 'HelloWorld',
    props: {
      msg: {
        type: String,
        default: ''
      }
    },
    setup() {
      const store = useStore(key)
      const count = computed(() => store.state.count)
      return {
        count,
        inCrement: () => store.commit('increment')
      }
    }
  })
</script>


4.2 vue-router


在 src 目录下建立 router/index.ts,内容如下:


import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import HelloWorld from "../components/HelloWorld.vue";
const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        name: "HelloWorld",
        component: HelloWorld,
    },
    {
        path: "/about",
        name: "About",
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () =>
            import(/* webpackChunkName: "About" */ "../components/About.vue")
    }
];
const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes,
});
export default router;


再新建一个 components/About.vue 文件,内容如下:


<template>
  <img
    alt="Vue logo"
    src="../assets/logo.png"
  />
  <h1>{{ msg }}</h1>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'About',
  data() {
    return {
      msg: 'Hello Vue 3.0 + Vite!'
    }
  },
  setup() {}
})
</script>


再修改 main.ts


import { createApp } from 'vue'
import { store, key } from './store'
import router from "./router";
import App from './App'
import './index.css'
const app = createApp(App)
app.use(store, key)
app.use(router)
app.mount('#app')


再访问 http://localhost:3000/


微信图片_20220513125001.png


http://localhost:3000/about 即可


微信图片_20220513123952.gif


5. 加入 Element Plus


5.1 安装 element-plus


全局安装


npm install element-plus --save

5.2 引入 Element Plus


你可以引入整个 Element Plus,或是根据需要仅引入部分组件。我们先介绍如何引入完整的 Element。


完整引入


在 main.js 中写入以下内容:


import { createApp } from 'vue'
import ElementPlus from 'element-plus';
import router from "./router";
import 'element-plus/lib/theme-chalk/index.css';
import App from './App.vue';
import './index.css'
const app = createApp(App)
app.use(ElementPlus)
app.use(router)
app.mount('#app')


以上代码便完成了 Element Plus 的引入。需要注意的是,样式文件需要单独引入。


按需引入


借助 babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的。


首先,安装 babel-plugin-component:


npm install babel-plugin-component -D


然后,将 .babelrc 修改为:


{
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-plus",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}


接下来,如果你只希望引入部分组件,比如 Button 和 Select,那么需要在 main.js 中写入以下内容:


import { createApp } from 'vue'
import { store, key } from './store';
import router from "./router";
import { ElButton, ElSelect } from 'element-plus';
import App from './App.vue';
import './index.css'
const app = createApp(App)
app.component(ElButton.name, ElButton);
app.component(ElSelect.name, ElSelect);
/* or
 * app.use(ElButton)
 * app.use(ElSelect)
 */
app.use(store, key)
app.use(router)
app.mount('#app')
app.mount('#app')


更详细的安装方法请看 快速上手


5.3 全局配置


在引入 Element Plus 时,可以传入一个全局配置对象。


该对象目前支持 sizezIndex 字段。size 用于改变组件的默认尺寸,zIndex 设置弹框的初始 z-index(默认值:2000)。按照引入 Element Plus 的方式,具体操作如下:


完整引入 Element:


import { createApp } from 'vue'
import ElementPlus from 'element-plus';
import App from './App.vue';
const app = createApp(App)
app.use(ElementPlus, { size: 'small', zIndex: 3000 });


按需引入 Element:


import { createApp } from 'vue'
import { ElButton } from 'element-plus';
import App from './App.vue';
const app = createApp(App)
app.config.globalProperties.$ELEMENT = option
app.use(ElButton);


按照以上设置,项目中所有拥有 size 属性的组件的默认尺寸均为 'small',弹框的初始 z-index 为 3000。

相关文章
|
19天前
|
资源调度 JavaScript 前端开发
Vue的路由管理:VueRouter的配置和使用
【4月更文挑战第24天】VueRouter是Vue.js的官方路由管理器,用于在单页面应用中管理URL路径与组件的映射。通过安装并引入VueRouter,设置路由规则和创建router实例,可以实现不同路径下显示不同组件。主要组件包括:`&lt;router-link&gt;`用于创建导航链接,`&lt;router-view&gt;`负责渲染当前路由对应的组件。此外,VueRouter还支持编程式导航和各种高级特性,如嵌套路由、路由参数和守卫,以应对复杂路由场景。
|
13天前
|
监控 JavaScript 前端开发
【JavaScript与TypeScript技术专栏】TypeScript在JavaScript项目中的渐进式采用
【4月更文挑战第30天】TypeScript是JavaScript的超集,引入静态类型、接口等特性,提升代码安全性和可读性。在JavaScript项目中采用TypeScript可享受类型安全、社区支持及优秀工具集成等优势。渐进式采用策略包括评估项目现状、逐步引入新旧模块、编写类型定义文件、配置编译选项和编写测试用例,以提高项目质量和效率。
|
13天前
|
JavaScript 前端开发 编译器
【JavaScript与TypeScript技术专栏】从JavaScript迁移到TypeScript的最佳实践
【4月更文挑战第30天】本文介绍了从 JavaScript 迁移到 TypeScript 的最佳实践。首先,学习 TypeScript 基础并安装编译器。接着,采取逐步迁移策略,保持与 JavaScript 兼容,利用类型定义和接口增强代码可读性。此外,借助 TSLint 和 Prettier 保证代码质量与风格一致性,使用类型定义文件提升第三方库的可维护性。
|
13天前
|
传感器 JavaScript 前端开发
【TypeScript技术专栏】TypeScript在大型项目中的实践与挑战
【4月更文挑战第30天】TypeScript在大型前端项目中日益流行,以其类型系统和ES6+支持提升代码安全与维护性。然而,采用 TypeScript 面临学习曲线、构建时间增加及类型推断挑战。通过最佳实践和成熟工具链(如 tsc、tslint 和 Visual Studio Code)可克服这些问题。案例如Angular、Basecamp和Slack已成功应用TypeScript。掌握TypeScript对提升开发者技能和市场竞争力至关重要。
|
13天前
|
JavaScript 前端开发 开发工具
【TypeScript 技术专栏】使用 TypeScript 重构 JavaScript 项目
【4月更文挑战第30天】TypeScript 在前端开发中日益流行,因其静态类型检查、增强代码可读性和更好的工具支持。本文讨论如何用 TypeScript 重构 JavaScript 项目,包括评估项目、安装 TypeScript 工具、逐步添加类型注解、处理兼容性问题以及解决重构中遇到的问题。重构后,代码质量、团队协作和可维护性均得到提升。通过实例分析,文章为 TypeScript 重构提供指导,助力构建更可靠的前端应用。
|
20天前
|
JavaScript IDE 编译器
TypeScript中模块路径解析与配置:深入剖析与最佳实践
【4月更文挑战第23天】本文深入探讨了TypeScript中模块路径解析的原理与配置优化,包括相对路径、Node.js模块解析和路径别名。通过配置`baseUrl`、`paths`、`rootDirs`以及避免裸模块名,可以提升开发效率和代码质量。建议使用路径别名增强代码可读性,保持路径结构一致性,并利用IDE插件辅助开发。正确配置能有效降低维护成本,构建高效可维护的代码库。
|
24天前
|
JavaScript 前端开发
ant design vue 配置菜单外部打开
ant design vue 配置菜单外部打开
16 0
|
27天前
vue3打包war压缩包配置
vue3打包war压缩包配置
19 0
|
27天前
|
JavaScript
vue3+vite项目配置ESlint
vue3+vite项目配置ESlint
52 0
|
27天前
乾坤子应用配置(vue3+vite)
乾坤子应用配置(vue3+vite)
72 0