Full project address: vue-element-admin
Series of articles:
- Hand touch hand, take you to use vue backstage series a (basic)
- Hand to hand, take you to use vUE masturbation background series two (login permission)
- Hand to hand, take you to use the vUE backstage series three (Actual combat)
- Hand touch, take you with vue Lute background series four (vueAdmin a minimalist background base template)
- Hand touch hand, take you to use vUE Background Lift series five (v4.0 new version)
- Hand to hand, take you to wrap a Vue Component
- Hand to hand, with your elegant use of icon
- Using webpack4 with proper posture (part 1)
- Using webpack4 with proper posture
preface
Said good tutorial finally came, the first article is mainly about some preparations before starting to write actual business code, but here will not teach you the basic configuration of Webpack, hot update principle is what, Webpack speed optimization and so on, there is a need to please Google, related articles have been a lot of.
The directory structure
├─ build │ ├─ config │ ├─ SRC // Source │ ├─ API │ ├─ Assets │ ├─ Components │ ├─ Directive │ ├─ Flag // All SVG ICONS │ ├─ lang // International Language │ ├─ Mock / / project mock simulation data │ ├ ─ ─ the router / / routing │ ├ ─ ─ store / / global store management │ ├ ─ ─ styles / / global style │ ├ ─ ─ utils / / global public method │ ├ ─ ─ Vendor / / public vendor │ ├ ─ ─ views / / view │ ├ ─ ─ App. Vue / / entry page │ ├ ─ ─ the main, js / / entry loading component initialization │ └ ─ ─ permission. Js / / rights management ├ ─ ─ the static / / the third party is not packaged resources │ └ ─ ─ Tinymce / / rich text ├ ─ ─ the babelrc / / Babel - loader configuration ├ ─ ─ eslintrc. Js / / eslint configuration items ├ ─ ─ the gitignore ├─ ├─ └─ package.json // git ignore ├─ faviconCopy the code
Here’s a quick look at the SRC file
API and views
A quick snapshot of the company’s back-end projects, there are about 40 or 50 API modules in the back-end right now
For example, the article module is all the API related to the article, so that no matter how the project is accumulated, the MAINTENANCE of API and views is still clear. Of course, there are some common API modules in the whole region, such as Qiniu Upload, remoteSearch and so on, these can be placed separately.
components
Components are used to place globally common components such as upload components, rich text, etc. Some page-level components are suggested to be placed under their respective views files for easy management. As shown in figure:
store
My personal advice here is not to use Vuex for vuex’s sake. Take the background project of our company for example, although it is relatively large, with dozens of business modules and dozens of permissions, the coupling degree between businesses is very low. Article module and comment module are almost two independent things, so there is no need to use VUEX to store data. Each page can store its own data. Of course, vuEX still needs to be used for unified management of some data, such as login token, user information, or some global personal preference Settings, etc. It is more convenient to use VUEX to manage, and of course, it needs to be combined with its own business scenarios. Anyway, don’t use vuex for vuex’s sake!
webpack
The webpack-template template is used as the base of vue-CLI. If you have any questions about this, please Google it. The configuration is described in other articles, so I won’t expand it here. Just a few things to note.
Jquery (this project has been removed)
The management background is different from the foreground project, and some third-party plug-ins are often used, but some plug-ins have to rely on jquery. For example, many rich text bases in the market are dependent on jquery, so we simply introduce them into the project to save time (only 34KB after gzip, And for years from cache, forget the nitpicking about size, these kilobytes are nothing compared to the improved development efficiency). But if the third party library code appearsAn error is reported directly. To achieve a similar effect, use the built-in webPackProvidePlugin
Plug-in, configuration is simple, just need
new webpack.ProvidePlugin({
$: 'jquery' ,
'jQuery': 'jquery'
})
Copy the code
$, jQeury, and window.jQuery will be used when webpack encounters the jQuery package exported from node_module.
alias
As projects grow larger and direct references to files become more complex, you need to use aliases. Some people prefer alias to point to the SRC directory and use the relative path to find the file
resolve: {
alias: {
'~': resolve(__dirname, 'src')}}/ / use
import stickTop from '~/components/stickTop'
Copy the code
Or you can
alias: {
'src': path.resolve(__dirname, '.. /src'),
'components': path.resolve(__dirname, '.. /src/components'),
'api': path.resolve(__dirname, '.. /src/api'),
'utils': path.resolve(__dirname, '.. /src/utils'),
'store': path.resolve(__dirname, '.. /src/store'),
'router': path.resolve(__dirname, '.. /src/router')}/ / use
import stickTop from 'components/stickTop'
import getArticle from 'api/article'
Copy the code
There is no good or bad right or wrong, just personal preference and team norms.
ESLint
Whether it’s a multi-team or individual project, code specification is important. Doing so not only largely avoids basic syntax errors, but also keeps the code readable. This so-called work to do a good thing, must first sharp device, personally recommend ESLint + VScode to write vue, absolutely have a kind of flying general feeling. The effect is as follows:
Install the ESLint plugin first
After installing and configuring ESLint, go back to VSCode for extension Settings and go to file > preferences > Settings to open the VSCode configuration file and add the following configuration
"files.autoSave":"off"."eslint.validate": [
"javascript"."javascriptreact"."html",
{ "language": "vue"."autoFix": true}]."eslint.options": {
"plugins": ["html"]}Copy the code
This way you can check and do some simple fixes each time you save based on your.eslintrc.js esLint rule. Here is a copy of my usual ESLint rule addresses, all simply commented in. Every team and team has their own code specification, it is good to unify, to create their own ESLint rules to upload to NPM, such as ele. me team config, Vue config.
Vscode plug-ins and configuration recommendations
Encapsulation axios
We often encounter some online bugs, but the test environment is difficult to simulate. You can easily configure the environment on the local debug line. Here the business encapsulates axios, the online code
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// Create an axios instance
const service = axios.create({
baseURL: process.env.BASE_API, / / API base_url
timeout: 5000 // Request timeout
})
// Request interceptor
service.interceptors.request.use(config= > {
// Do something before request is sent
if (store.getters.token) {
config.headers['X-Token'] = getToken() // Let each request carry token--[' x-token '] is a custom key. Change it according to the actual situation
}
return config
}, error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
})
// Respone interceptor
service.interceptors.response.use(
response= > response,
/** * the following comment indicates the request status through the custom code, if the code returns as follows: permission problem, log out and return to the login page */
// const res = response.data;
// if (res.code ! = = 20000) {
// Message({
// message: res.message,
// type: 'error',
// duration: 5 * 1000
/ /});
// // 50008: Invalid token; 50012: Another client is logged in. 50014:Token expired;
// if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// messagebox.confirm (' you have been logged out, you can cancel to remain on this page, or log in again ', 'sure to log out ', {
// confirmButtonText: 'relogin ',
// cancelButtonText: 'cancel ',
// type: 'warning'
// }).then(() => {
// store.dispatch('FedLogOut').then(() => {
// location.reload(); // To re-instantiate vue-Router objects to avoid bugs
/ /});
/ /})
/ /}
// return Promise.reject('error');
// } else {
// return response.data;
/ /}
error => {
console.log('err' + error)// for debug
Message({
message: error.message,
type: 'error'.duration: 5 * 1000
})
return Promise.reject(error)
})
export default service
Copy the code
import request from '@/utils/request'
/ / use
export function getInfo(params) {
return request({
url: '/user/info'.method: 'get',
params
});
}
Copy the code
For example, in the background project, every request is required to bring token to verify permissions, so as to encapsulate the following: we do not need to manually remove token for every request, or to do some unified exception handling, once and for all. And since our API is dynamically switched based on the env environment variable, if a bug occurs online later, we can simply configure @/config/dev.env.js and restart the service to simulate the online environment locally.
module.exports = {
NODE_ENV: '"development"',
BASE_API: '"https://api-dev"'// Change to'"https://api-prod"'We have to do is APP_ORIGIN:'"https://wallstreetcn.com"'Vue + SSR}Copy the code
Mom doesn’t have to worry about my debug line bugs anymore. Of course, this is just a quick example. Axios can also execute multiple concurrent requests, interceptors, and so on.
Many environmental
Vue-cli provides only dev and PROd environments by default. However, the real development process may also include a SIT or stage environment, which is called a test environment and a pre-release environment. So we’re going to have to make a simple change to the code. It’s very simple to set different environment variables
"build:prod": "NODE_ENV=production node build/build.js"."build:sit": "NODE_ENV=sit node build/build.js".Copy the code
And then you do whatever you want in the code
var env = process.env.NODE_ENV === 'production' ? config.build.prodEnv : config.build.sitEnv
Copy the code
The new vuE-CLI also has a module called Webpack-bundle-Analyzer built in, which is pretty handy. It is also very simple to use, as before, just encapsulate an NPM script.
//package.json
"build:sit-preview": "cross-env NODE_ENV=production env_config=sit npm_config_preview=true npm_config_report=true node build/build.js"
// Then use process.env.npm_config_report to determine whether to enable webpack-bundle-Analyzer
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
Copy the code
rendering
Pack to force
Front and back end interaction
Every company has its own development process, there is no absolute good or bad. Here I will talk about the front and back end interaction process of our company.
Cross-domain problem
First of all, the front and back end interaction will inevitably encounter cross-domain problems, our company is now all using CORS to solve, if you are too troublesome to configure the back end of the dev environment can also be solved by webpack-dev-server proxy, development environment with nginx anti-proxy is good. I won’t expand the configuration here.
Front and back end interaction problems
As you all know, communication costs take up a large part of our development time, but a good way to collaborate on the front and back end can solve a lot of time. In the development process of our company, the front and back end meet with the product to discuss the project. After that, the back end first defines the data format and API according to the requirements, and then the mock API generates documents. Our front end is the interface docking. A document generator, Swagger, is recommended. Swagger is a REST API documentation tool that can be automatically generated from code comments on many different platforms. It is open source, supports most languages, and has a good community.
Front-end self-mock
If the back end won’t mock the data for you, it’s easy for the front end to mock it for you. You can use mock Server or mockJS + rap for convenience. Easy-mock, which comes out recently, is also quite good and combines swagger. We finally don’t have to look at the front end of the face ~
iconfont
There are not many default ICONS in Element-UI. Here, the IconFont of Amway Ali is a magic tool, which is used in both corporate projects and personal projects. It provides PNG, AI, SVG format, but also supports Unicode, font-class, symbol format. Because the management background does not have high requirements for compatibility, the owner of the building usually likes to use symbol to display a wave of our company’s background ICONS (all played by the owner himself).
Hand to hand, with your elegant use of icon
router-view
Different Router The same Component vue In real business scenarios, this happens a lot. Such as
<router-view :key="key"></router-view>
computed: {
key() {
return this.$route.name ! == undefined? this.$route.name + +new Date(): this.$route + +new Date()
}
}
Copy the code
To optimize the
Some people may think that it is a little slow to build now. Our company’s current technology stack is container service, and the background project will package everything in the Dist folder into a Docker image. The basic steps are as follows
NPM install NPM run build:prod The total time is as followsCopy the code
Still in the acceptable time range. The master PC station realizes server-side rendering based on NodeJS and Vue, so it not only needs to rely on NodeJS, but also needs to use PM2 to manage nodeJS life cycle. In order to speed up the online image construction, we use Taobao source registry.npm.taobao.org to speed it up, and put some common NPM dependencies into the basic image to avoid the need to re-download every time. Do not install or update the CNPM package. It is recommended to use CNPM install or update the CNPM package
npm install --registry=https://registry.npm.taobao.org
Copy the code
If you feel slow still there is room to optimize such as using the webpack DLL or those third-party vendor packaging external out alone, or we use is http2 can now use AggressiveSplittingPlugin, etc., there are needs to be optimized.
Of the pit
Conventional occupy pit, here is the hand touch hand, take you with vue lift backstage series. Full project address: vue-element-admin
-
Hand touch hand, take you to use vue backstage series a (basic)
-
Hand to hand, take you to use vUE masturbation background series two (login permission)
-
Hand to hand, take you to use the vUE backstage series three (Actual combat)
-
Hand touch, take you with vue Lute background series four (vueAdmin a minimalist background base template)
-
Hand touch hand, take you to use vUE Background Lift series five (v4.0 new version)
-
Hand to hand, take you to wrap a Vue Component
-
Hand to hand, with your elegant use of icon
-
Using webpack4 with proper posture (part 1)
-
Using webpack4 with proper posture