• The warehouse address, welcome to use,Star.

Why useVite

  1. Quick cold start
  2. Instant module hot update
  3. True on-demand compilation

Initialize the project

  • Create one quickly using the commands provided on the websiteVue3.0 + Vite2.0The project.
# NPM 6. X NPM init @vitejs/app my-vue-app --template vue # NPM 7+  npm init @vitejs/app my-vue-app -- --template vue # yarn yarn create @vitejs/app my-vue-app --template vueCopy the code

addElement-ui

  • Note: What we need to introduce iselement-plusRather thanelement-ui(element-plusThe adapter isVue3.0).

All components loaded

yarn add -S element-plus
Copy the code
  • Modify themain.js
import { createApp } from 'vue';
import App from './App.vue';

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

- createApp(App).mount('#app');
Copy the code

Components are loaded on demand

The use of plug-in
  1. usevite-plugin-babel-import
yarn add vite-plugin-babel-import -D
Copy the code
  • Modify thevite.config.js
+ import vitePluginImport from 'vite-plugin-babel-import';
export default defineConfig({
    ...
    plugins: [
        ...,
+       vitePluginImport([
+           {
+               libraryName: 'element-plus',
+               libraryDirectory: 'es',
+               style(name) {
+                   return `element-plus/lib/theme-chalk/${name}.css`;
+               },
+           },
+       ])
    ]
})
Copy the code
  1. usevite-plugin-style-import
yarn add vite-plugin-style-import -D
Copy the code
  • Modify thevite.config.js
    • Pay attention tostyleImportThe name cannot be changed
+ import styleImport from 'vite-plugin-style-import'; export default defineConfig({ ... Plugins: [..., + styleImport({// note that styleImport cannot be changed + libs: [{+ libraryName: 'element-plus', + esModule: true, + ensureStyleFile: true, + resolveStyle: (name) => {// introduce.scss style + // eslint-disable-next-line no-param-reassign + name = name.slice(3); + return `element-plus/packages/theme-+halk/src/${name}.scss`; + }, + // resolveStyle: (name) => 'elemental-plus /lib/theme-chalk/${name}. CSS', // introduce.css style + resolveComponent: (name) => `element-+lus/lib/${name}`, + }], + }), ] })Copy the code
Modify themain.js
/ / @ need to configure the SRC path alias, talk about behind + import element from '@ / common/element/components; - import ElementPlus from 'element-plus'; - import 'element-plus/lib/theme-chalk/index.css'; + / / set the global unification attribute + app config. GlobalProperties. $ELEMENT = {size: 'small', zIndex: 3000}; // Register the Element plugin element(app);Copy the code
increasecomponents.js
// src/common/element/components.js' import { ElAlert, ElAside, ... // Import the required components ElInfiniteScroll... // import required plugins]; export const components = [ ElAlert, ElAside, ... ]  export const plugins = [ ElInfiniteScroll, ElLoading, ElMessage, ElMessageBox, ElNotification, ]; Export default (app) => {components. ForEach ((component) => {app.component.name, component); }); plugins.forEach((plugin) => { app.use(plugin); }); };Copy the code

addESLint

  • I’ve always been used to usingairbnbThat set of norms, you can choose other ones.
yarn add -D eslint eslint-config-airbnb-base eslint-plugin-import eslint-plugin-vue
Copy the code
  • increaseESLintConfiguration file of.eslintrc.js.
module.exports = { extends: ['plugin:vue/vue3-essential', 'airbnb-base'], parserOptions: { ecmaVersion: Indent: [2, 4], 'no-unused-vars': [2, {vars: 'all', / / "local", allow the statement did not use the variable args: 'all', / /}], check all parameters, overrides: [{} files: [' *. Vue '], rules: {/ / write here cover the rules of the vue file 'no - unused - vars' : [0],},},]};Copy the code
  • Cooperate withVS CodeThe plug-inbeautify, simple error save automatic repair.All the rules
// settings.json { ... , "editor.formatOnSave": true, // # Automatically format "editor.codeActionsOnSave": {// Automatically fix "source. fixall. eslint": True,}, "eslint.validate": ["javascript", "vue", "HTML "],// Configure the file type "eslint.options" for esLint: {/ / specified vscode eslint processing the file suffix "extensions" : [", "vue" js ", "ts" and "benchmark"]}, "beautify. Language" : {" js ": {" type" : [ "javascript", "json" ], "filename": [ ".jshintrc", ".jsbeautify" ] }, "css": [ "css", "scss" ], "html": }, "[json]": {"editor.defaultFormatter": "hookyqr.beautify"}}Copy the code
  • addESLintThe checked configuration file is ignored.eslintignore
// You can add /node_modules /dist *.html as you likeCopy the code

addSASSpretreatment

  • The installation
yarn add -D sass
Copy the code
  • ViteThe introduction ofSASSGlobal variables/styles,Vite1.0and2.0The writing method is not quite the same, there are changes pleaseTo view the document.
// vite.config.js import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; export default defineConfig({ ... , CSS: {preprocessorOptions: {SCSS: {// Note: the key name is SCSS not sass! / / here you want to import the global SCSS variable path, only write relative paths, alias will not take effect in CSS seems additionalData: "@ import '. / SRC/assets/SCSS/reset. SCSS '; @import './src/assets/scss/variable.scss';" , }, }, }, plugins: [vue()], });Copy the code

Adding an Alias Configuration

  • Modify thevite.config.js.
// vite.config.js
+ import path from 'path';
export default defineConfig({
+    resolve: {
+        alias: [{
+            find: '@',
+            replacement: path.join(__dirname, 'src'),
+        },],
+    },
     ...
});
Copy the code
  • Modify the.eslintrc.js.
//.eslintrc.js module.exports = {+ Settings: {// @exports = 'import/resolver': {+ alias: {+ map: [ + ['@', './src'], + ], + extensions: ['.ts', '.js', '.jsx', '.json', '.vue'], + }, + }, + }, ... }Copy the code
  • After configuration, discover use@Importing files is still reporting errors.

  • in.eslintrc.jsAdd a rule to the rule.
Module. exports = {rules: {+ 'import/no-absolute-path': [0], // disable module export with absolute path}}Copy the code

configurationvue-router

Install the appropriate packages

yarn add -S vue-router; / / 4Copy the code

addrouterDirectory and corresponding files

  • addindex.jsFile.
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import routes from './routes';

const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;
Copy the code
  • addroutes.jsFile.
// src/router/routes.js
const home = () => import('@/pages/home/index.vue');
const login = () => import('@/pages/login/index.vue');
const Page404 = () => import('@/components/Page404.vue');

const routes = [
    { path: '/', redirect: '/login' },
    {
        path: '/home',
        name: 'home',
        component: home,
    },
    {
        path: '/login',
        name: 'login',
        component: login,
    }, {
        path: '/:catchAll(.*)',
        name: '404',
        component: Page404,
    },
];
export default routes;
Copy the code
  • Add the page file tohomePage as an example, all the code please go to the warehouse to viewThe warehouse address.
// src/pages/home/index.vue
<template>
  <p>home</p>
  <el-button type="primary" @click="toLogin">Login</el-button>
</template>
<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();
const toLogin = (() => {
    router.push({
        name: 'login',
    });
});
</script>
Copy the code

Add Submit validation

addhusky

  • Husky official documentation
  1. The installationhuskyAnd enable thegit hooks
npx husky add .husky/pre-commit "npm run lint"
Copy the code
  1. Modify thepackage.jsonfile
// package.json { scripts: { ... , "lint": "eslint . --ext .js,.ts,.vue --ignore-path .gitignore", "prepare": "husky install" }, }Copy the code
  1. addcommitSubmission specificationgit hooks
npx husky add .husky/commit-msg 'yarn commitlint --edit "$1"'
Copy the code
  1. addcommitlint.config.jsAnd related dependencies
/ / rely on yarn add @ commitlint/cli @ commitlint/config - but - D / / commitlint. Config. Js module. Exports = {extends: ['@commitlint/config-conventional'], rules: { 'type-enum': [ 2, 'always', ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore'], ], 'subject-full-stop': [0, 'never'], 'subject-case': [0, 'never'], }, }; // Only the following seven identifiers are allowed for the commit content. // feat: new features // fix: bug // docs: Documentation // style: // Refactoring (i.e. not new features or code changes to fix bugs) // test: adding tests // chore: changes to the build process or chore toolsCopy the code

addlint-staged

  • Lint-staged official documentation
  • lint-stagedWhen we submit the code, we will only check and repair the modified file, so as to ensure that the submitted code does not have grammatical errors and will not affect the failure of other partners in updating the code.
  1. The installation
yarn add lint-staged -D
Copy the code
  1. add.lintstagedrcConfiguration files and dependencies
  • Stylelint rule document
Lintstagedrc {"*.{js,ts,vue}": ["npm run lint"], "*.{html,vue,css,scss,sass,less}": ["stylelint --fix"] }Copy the code
  1. Modify thepre-commitfile
// .husky/pre-commit #! /bin/sh . "$(dirname "$0")/_/husky.sh" - npm run lint + yarn lint-staged --allow-empty "$1"Copy the code

Test code review and submission specifications

  • VS Code configuration
  1. Code review

2. gitSubmit specifications

Added the multi-language configuration

Install dependencies

yarn add vue-i18n -S
Copy the code

Add the lang directory and language configuration file

  • increasesrc/lang/en.js
// src/lang/en.js
export default {
    user: {
        name: 'Detanx',
        changeLang: 'Change Language',
    },
    home: {
        toLogin: 'To Login',
    },
    login: {
        toHome: 'To Home',
    },
};
Copy the code
  • increasesrc/lang/zh-cn.js
// SRC /lang/zh-cn.js export default {user: {name: 'xiao xiao 17 ', changeLang:' switch language ',}, home: {toLogin: 'login ',}, login: {toHome: 'home ',},};Copy the code
  • increasesrc/lang/index.js
// src/lang/index.js import { createI18n } from 'vue-i18n'; import elementlangEn from 'element-plus/lib/locale/lang/en'; import elementlangZhCn from 'element-plus/lib/locale/lang/zh-cn'; import localeLangEn from './en'; import localeLangZhCn from './zh-cn'; const messages = { en: { ... localeLangEn, ... elementlangEn, }, 'zh-cn': { ... localeLangZhCn, ... elementlangZhCn, }, }; const i18n = createI18n({ locale: localStorage.getItem('lang') || 'zh-cn', messages, }); export default i18n;Copy the code

Modify the main js

// main.js import { createApp } from 'vue'; import element from '@/common/element/components'; + import ElementLocale from 'element-plus/lib/locale'; + import i18n from '@/lang'; import App from './App.vue'; import router from './router'; + ElementLocale.i18n((key, value) => i18n.global.t(key, value)); const app = createApp(App); app.config.globalProperties.$ELEMENT = { size: 'small', zIndex: 3000 }; // Register the Element plugin element(app); app.use(router); + app.use(i18n); app.mount('#app');Copy the code

Modifying page files

// src/pages/home/index.vue <template> - <p>home</p> - <el-button type="primary" @click="toLogin">Login</el-button> + <el-button type="primary" @click="$i18n.locale = $i18n.locale === 'en' ? 'zh-cn' : 'en'"> + {{$t("user.changeLang")}} + </el-button> + <p style="margin: 10px;" >{{$t("user.name")}}</p> + <el-button type="primary" @click="toLogin">{{$t("home.toLogin")}}</el-button> </template> ...Copy the code

Demonstration of test results

i18n-test.mov

Past wonderful

  • “Front-end advanced” JavaScript handwriting methods/use tips self-check
  • An introduction to JavaScript design patterns and creative patterns
  • Public account open small program best solution (Vue)
  • Axios you probably don’t know how to use

“Likes, favorites and comments”

❤️ follow + like + favorites + comments + forward ❤️, creation is not easy, encourage the author to create a better article, thank 🙏 everyone.