The larger version of Vue3.0 has been around for a while and is already mature.

And since Element Plus + Vite has been around for a while, it’s time for a wave of hands-on sharing.

The main thing is to get familiar with Vue3 and prepare to use Vue3 to reconfigure my own website project: blog-vue-typescript. The plan is to start reconstructing this project during the New Year and launch it after the New Year.

1. Initial project

Install viet-app globally

npm i -g vite-app
Copy the code

Create a project

Yarn create viet-app <project-name> # NPM init viet-app <project-name>Copy the code

Enter the project and install the dependencies

CD <project-name> YARN # or NPM ICopy the code

Run the project

yarn dev 
Copy the code

Open your browser http://localhost:3000

2. Introduce the TypeScript

Adding TS dependencies

yarn add --dev typescript
Copy the code

Create the TypeScript configuration file tsconfig.json in the project root directory

{
  "compilerOptions": {
    // Allow default imports from modules that do not have default exports set. This does not affect the output of the code, just for type checking.
    "allowSyntheticDefaultImports": true.// Resolve the base directory for non-relative module names
    "baseUrl": "."."esModuleInterop": true.// Import helper functions from tslib (such as __extends, __rest, etc.)
    "importHelpers": true.// Specify which module system code to generate
    "module": "esnext".// Decide what to do with the module.
    "moduleResolution": "node".// Enable all strict type checking options.
    // Enable --strict = enable --noImplicitAny, --noImplicitThis, --alwaysStrict,
    / / - strictNullChecks and - strictFunctionTypes and - strictPropertyInitialization.
    "strict": true.// Generate the corresponding.map file.
    "sourceMap": true.// Ignore type checking for all declaration files (*.d.ts).
    "skipLibCheck": true.// Specify the ECMAScript target version
    "target": "esnext".// The type to include declares a list of file names
    "types": []."isolatedModules": true.// List of module names to baseUrl pathmaps.
    "paths": {
      "@ / *": [
        "src/*"]},// A list of library files that need to be imported during compilation.
    "lib": [
      "ESNext"."DOM"."DOM.Iterable"."ScriptHost"]},"include": [
    "src/**/*.ts"."src/**/*.tsx"."src/**/*.vue"."tests/**/*.ts"."tests/**/*.tsx"]."exclude": [
    "node_modules"]}Copy the code

Add a new shim.d.ts file to the SRC directory

/* eslint-disable */
import type { DefineComponent } from 'vue'

declare module '*.vue' {
  const component: DefineComponent<{}, {}, any>
  export default component
}
Copy the code

Change main.js to main.ts

In the root directory, open index.html

<script type="module" src="/src/main.js"></script> Change to <script type="module" src="/src/main.ts"></script>
Copy the code

3. Introduce the eslint

Install the esLint prettier dependency

@typescript-eslint/parser @typescript-eslint/ eslint-plugin Is support for typescript in ESLint.

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

Create the esLint configuration file.eslintrc.js in the root directory

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']}};Copy the code

Establish a prettier. Config. Js

module.exports = {
  printWidth: 100.tabWidth: 2.useTabs: false.semi: false.// Open comma
  vueIndentScriptAndStyle: true.singleQuote: true./ / single quotation marks
  quoteProps: 'as-needed'.bracketSpacing: true.trailingComma: 'none'.// Final semicolon
  jsxBracketSameLine: false.jsxSingleQuote: false.arrowParens: 'always'.insertPragma: false.requirePragma: false.proseWrap: 'never'.htmlWhitespaceSensitivity: 'strict'.endOfLine: 'lf'
}
Copy the code

4. Vue – the router, vuex

yarn add vue-router@next vuex@next
Copy the code

4.1 vuex

Create store/index.ts in the root directory

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++
    }
  }
})
Copy the code

The main ts change

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')
Copy the code

The components/HelloWord vue modification

<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>Copy the code

4.2 the vue – the router

Create router/index.ts in the SRC directory as follows:

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;
Copy the code

Create a new components/ about.vue file with the following contents:

<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>
Copy the code

To modify the 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')
Copy the code

And then visit http://localhost:3000/

And http://localhost:3000/about

5. Join Element Plus

5.1 installation element – plus

Global installation

npm install element-plus --save
Copy the code

5.2 Introducing Element Plus

You can introduce the whole Element Plus, or just a few components as needed. Let’s start by introducing a complete Element.

A complete introduction

Write the following in 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')
Copy the code

This completes the introduction of Element Plus. Note that style files need to be introduced separately.


According to the need to introduce

With babel-plugin-Component, we can reduce the size of the project by introducing only the components we need.

First, install the babel-plugin-Component:

npm install babel-plugin-component -D
Copy the code

Then, change.babelrc to:

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

Next, if you want to introduce only a few components, such as Button and Select, you need to write the following in 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')
Copy the code

For more detailed installation methods, see Quickstart.

5.3 Global Configuration

When you introduce Element Plus, you can pass in a global configuration object.

The object currently supports the size and zIndex fields. Size is used to change the default size of the component, and zIndex sets the initial Z-index of the pop-up (default: 2000). According to the way of introducing Element Plus, the specific operations are as follows:

Complete introduction of 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 });
Copy the code

Introduce elements on demand:

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);
Copy the code

According to the above Settings, the default size of all components in the project with the size attribute is ‘small’, and the initial z-index of the pop-up box is 3000.

The last

With a Vue3 family bucket + Vite + TypeScript + Eslint + Element Plus development environment now in place, you’re ready to write code.

Refer to their respective documentation for the use of each component.

Vue3 + Element Plus + Vite + TypeScript really smells good!

Recommend a Vue3 related information summary: Vue3 learning tutorial summary, source code interpretation project, support UI component library, quality actual combat project, I believe you will dig to mine oh!

Vue3 Chinese document, domestic CDN accelerated version:

vue3js.cn/docs/zh/

Element Plus website:

element-plus.org/#/zh-CN


As the second original technical article of 2021, the quality should be ok, KPI is completed in January, hahaha 😅

The end of the year for Cat brother is here: front-end engineer’s end of the year for 2020 – the world is uncertain, you and I are dark horse, hope to give you a little inspiration, also see cat brother’s face is beaten slanting 😂

See article: Vue3 + Vite + typescript + ESLint + JEST project configuration practices

Recommended reading

  • 10 Advanced Tips for Improving Happiness in TypeScript