“This is my NTH day of participating in the First Challenge 2022. For details: First Challenge 2022.”
preface
Hi, I’m Asscre.
Recently, I took over a Web front-end project, and decided to choose Vue3 framework to build the project by analyzing the technical stack and Javascript mastery of the company’s staff.
Here, summarize the architecture building process after the technology selection.
Train of thought
Vue2 (Long Long ago), which has been used before, is also built based on our previous development experience.
- Framework: Vue3
- API request: Axios
- Route management: VUe-router
- Status management: Vuex
- Css library: Tailwind Css
- UI component library: Element UI
- Code check: Eslint
- Code formatting: Prettier
Below, we set up the project architecture in turn.
Come out with a basic project
Initialize the project and install Vue3
npm create vite@latest
Copy the code
// Install depends on NPM I // run NPM run devCopy the code
API request: Axios
npm install axios
Copy the code
Route management: VUe-router
npm install vue-router@4
Copy the code
Create three pages
// home page <template> <div>home page</div> <button @click="toAbout">toAbout</button> </template> <script setup> import router from '.. /routes'; const toAbout = () => { router.push('./about'); }; </script> // about page <template> <div>about page</div> <button @click="toHome">toHome</button> </template> <script setup> import router from '.. /routes'; const toHome = () => { router.push('/'); }; </script> // 404 page <template> <div>404</div> </template>Copy the code
Initializing a Route
import { createRouter, createWebHistory } from 'vue-router';
import Home from '.. /pages/home.vue';
import About from '.. /pages/about.vue';
import NotFound from '.. /pages/not-found.vue';
const routes = [
{
path: '/'.component: Home,
meta: { title: 'Home'}, {},path: '/About'.component: About,
meta: { title: 'About' },
// example of 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('./views/About.vue')
},
{ path: '/:path(.*)'.component: NotFound },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// Route global front-guard
router.beforeEach((to, from, next) = > {
// console.log(" Route global front-guard ", to, from);
next();
});
// Route global post guard
router.afterEach((to, from, next) = > {
console.log('Route global post Guard', to, from);
next();
});
export default router;
Copy the code
Registered routing
/main.js
import { createApp } from 'vue';
// import './tailwind.css';
import App from './App.vue';
import router from './routes';
createApp(App).use(router).mount('#app');
Copy the code
src/App.vue
<template>
<router-view />
</template>
Copy the code
Effect display:
Status management: Vuex
npm install vuex@next --save
Copy the code
Initialization vuex SRC/store/index. Js
import { createStore } from 'vuex';
const store = createStore({
state() {
return {
count: 0}; },mutations: {
increment(state){ state.count++; ,}}});export default store;
Copy the code
Mount:
import { createApp } from 'vue';
import App from './App.vue';
import router from './routes';
import store from './store';
createApp(App).use(router).use(store).mount('#app');
Copy the code
Use:
<template> <div>home page</div> <p>{{ store.state.count }}</p> <button @click="toAbout">toAbout</button> <button @click="increment">+</button> </template> <script setup> import router from '.. /routes'; import store from '.. /store'; const toAbout = () => { router.push('./about'); }; const increment = () => { store.commit('increment'); console.log(store.state.count); }; </script>Copy the code
Effect:
Css library: Tailwind Css
Tailwind CSS works by scanning all your HTML files, JavaScript components, and any other templates for class names, generating the appropriate styles, and then writing them to static CSS files.
The resulting styles are atomic Css.
- Install the Tailwind CSS
Because we use Vite to create projects, since we want to make it easy for developers to respond quickly to development, we need to use PostCSS to help us quickly listen to generate CSS styles.
Install tailwindCSS and its peer dependencies through NPM and create your files. tailwind.config.js
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
Copy the code
Add tailwindCSS and autoprefixer to your files, or configure PostCSS anywhere in your project. postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},}}Copy the code
Add the path tailwind.config.js for all template files to the file.
module.exports = {
content: ['./src/**/*.{html,js,vue}'],
theme: {
extend: {},
},
plugins: [],
};
Copy the code
Tailwind adds instructions for each layer of tailwind to your main CSS file.
/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Copy the code
NPM run dev runs the build process package.json using the commands configured in the file or any commands.
npm run dev
Copy the code
/main.js to introduce tailwindCSS
import './tailwindcss.css';
Copy the code
Modify the home Page code to look like this:
UI Component library: Import Element UI on demand
npm install -D unplugin-vue-components unplugin-auto-import
Copy the code
Import Element in viet.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
});
Copy the code
Code formatting: Prettier
npm install --save-dev --save-exact prettier
Copy the code
Next we will create a configuration file for Prettier.
Because Prettier aims for out-of-the-box configuration, the contents of the configuration file can be just an empty object. We just added it because some ides use its presence to detect more beautifully. If you want to configure one of the few options Prettier does provide, see the Documentation for Configuring options for Prettier.
echo {}> .prettierrc.json
Copy the code
Code check: Eslint
npm install --save-dev eslint eslint-plugin-vue
Copy the code
Next, we’ll configure ESLint by creating a.eslintrc.js file with the following configuration to configure it to use ESLint recommendation rules as well as Vue 3 recommendation rules.
module.exports = {
env: {
node: true,
},
extends: [
'eslint:recommended',
'plugin:vue/vue3-recommended',
],
rules: {
// override/add rules settings here, such as:
// 'vue/no-unused-vars': 'error'
}
}
Copy the code
If necessary, visit the eslint-plugin-Vue documentation to see additional configurations available for VUE 3 for less stringent options. Different configurations correspond to three different priorities in vue.js 3 Style Guide.
Handling Prettier conflicts with ESLint format rules
Finally, we’ll close the ESLint format rule that conflicts with Prettier. If we don’t perform this step, we’ll have a never-ending death match between 2 that looks something like this:
If you didn’t realize this when you set Prettier and ESLint, you probably never want to use them again! Fortunately, it’s easy to fix.
We just need to install the eslint-config-prettier configuration. This disables formatting rules in ESLint, which Prettier will be responsible for handling.
npm install eslint-config-prettier --save-dev
Copy the code
.eslintrc.js and register the configuration in a file under extends. Make sure it is the last configuration defined in the extended array, because the order of the configurations determines the handling of duplicate rules in different configurations (later configurations overwrite previous configurations)!
//.eslintrc.js
extends: [
'eslint:recommended',
"plugin:vue/vue3-recommended",
"prettier"
],
Copy the code
Run from the command line
At this point, we should set ESLint to report and correct fixable errors, and Prettier to reformat our source code. Let’s add the following two items to the scriptspackage.json section.
"scripts":{
//...
"lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
"format": "prettier . --write"
}
Copy the code
The Lint command defined here is ideal for running Lint in a CI/CD pipe or just for manual testing on a terminal. You can quickly look at any of these by running the corresponding commands, but that’s not necessarily how you want to keep using them throughout your development.
Set ESLint and Prettier for Vue 3 using VS Code
To simplify your workflow, you need to integrate these two tools with your IDE. Doing so allows you to underline errors in real time and provides automatic fixes for ESLint errors and a prettier format for file saving. Talk about saving time! Since VS Code is a free and popular IDE, and the one I use, let’s take a look at how ESLint and Prettier can be integrated with VS Code into your Vite driver’s vue.js 3 project.
First, you need to install two plug-ins for Prettier and ESLint. If you haven’t already installed Vetur, you’ll need to, because it provides syntax highlighting and more for.vue files.
Next, in your VS code setup, you should provide the following to turn off Vetur validation of templates and have ESLint handle it according to the rules in the.eslintrc.js file.
// Code/User/settings.json
"vetur.validation.template": false
Copy the code
Now, if you open the HelloWorld component, you can see that ESLint is running. You can see the yellow wavy line MSG: String below, and if you hover over it you can see more information about why ESLint is warning you. In this case, this is because of the rule vue/require-default-prop.
So to solve this problem, we can do one of two things.
- If we want to allow items without default values, we can
vue/require-default-prop
Close the rule in the file..eslintrc.js
// Code/User/settings.json
rules: {
//...
"vue/require-default-prop": "off",
},
Copy the code
- Or we change the code to comply with the rules by providing defaults, and the wavy line disappears! Very good!
Now we have ESLint reporting errors directly in files, but we don’t have any automatic Settings to let Prettier reformat code or to let ESLint automatically correct fixable problems. We can tell the VS code to do both at save time by adding the following to our VS code Settings.
// Code/User/settings.json
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
}
Copy the code
We should also make sure that our Vue and JS files are configured to look prettier with the default formatter with the following Settings:
// Code/User/settings.json
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
Copy the code
Now, if you open app.vue and put the image on one and save it, it will automatically bounce back to where it should be! More beautiful at work!
If you change the image to a fictitious array of items looping in front of the key, the V-for looks like this:
<img :key="i" v-for="i in items" alt="Vue logo" src="./assets/logo.png" />
Copy the code
You’ll see ESLint put the vue/ Attributes-Order rule into effect, automatically fixing the problem when saving. It’s so convenient!
ESLint error in browser
Our current setup is probably enough to increase productivity for most developers and teams. However, if you want to go one step further, you can install the Vite ESLint plug-in to view ESLint issues overlaid on your application in a browser.
This makes ESLint errors that cannot be fixed automatically impossible to ignore. I know some developers and others who like this find it super annoying, so install it if you want, otherwise just make sure you pay special attention to those red curves in your IDE.
vite-plugin-eslint
By running theThe installation
npm install vite-plugin-eslint --save-dev
Copy the code
Then register the plug-in by importing it and add it to the plug-in vite.config.js
import { defineConfig } from 'vite';
import eslintPlugin from 'vite-plugin-eslint';
export default defineConfig({
plugins: [eslintPlugin()],
});
Copy the code
That’s it, any ESLint errors will now be reported in the browser! If it does not suit you, try restarting development Server.
Attach the project template
vite-vue3-template
I’m Asscre. If you see this, give it a thumbs up!
Wechat official account: Asscrecn. Let’s grow together.