- The warehouse address, welcome to use,
Star
.
Why useVite
- Quick cold start
- Instant module hot update
- True on-demand compilation
Initialize the project
- Create one quickly using the commands provided on the website
Vue3.0 + Vite2.0
The 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 is
element-plus
Rather thanelement-ui
(element-plus
The adapter isVue3.0
).
All components loaded
yarn add -S element-plus
Copy the code
- Modify the
main.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
- use
vite-plugin-babel-import
yarn add vite-plugin-babel-import -D
Copy the code
- Modify the
vite.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
- use
vite-plugin-style-import
yarn add vite-plugin-style-import -D
Copy the code
- Modify the
vite.config.js
- Pay attention to
styleImport
The name cannot be changed
- Pay attention to
+ 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 using
airbnb
That 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
- increase
ESLint
Configuration 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 with
VS Code
The 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
- add
ESLint
The checked configuration file is ignored.eslintignore
// You can add /node_modules /dist *.html as you likeCopy the code
addSASS
pretreatment
- The installation
yarn add -D sass
Copy the code
Vite
The introduction ofSASS
Global variables/styles,Vite1.0
and2.0
The 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 the
vite.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.js
Add 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
addrouter
Directory and corresponding files
- add
index.js
File.
// 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
- add
routes.js
File.
// 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 to
home
Page 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
- The installation
husky
And enable thegit hooks
npx husky add .husky/pre-commit "npm run lint"
Copy the code
- Modify the
package.json
file
// package.json { scripts: { ... , "lint": "eslint . --ext .js,.ts,.vue --ignore-path .gitignore", "prepare": "husky install" }, }Copy the code
- add
commit
Submission specificationgit hooks
npx husky add .husky/commit-msg 'yarn commitlint --edit "$1"'
Copy the code
- add
commitlint.config.js
And 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-staged
When 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.
- The installation
yarn add lint-staged -D
Copy the code
- add
.lintstagedrc
Configuration files and dependencies
- Stylelint rule document
Lintstagedrc {"*.{js,ts,vue}": ["npm run lint"], "*.{html,vue,css,scss,sass,less}": ["stylelint --fix"] }Copy the code
- Modify the
pre-commit
file
// .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
- Code review
2. git
Submit specifications
Added the multi-language configuration
Install dependencies
yarn add vue-i18n -S
Copy the code
Add the lang directory and language configuration file
- increase
src/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
- increase
src/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
- increase
src/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.