Alone in the company overtime night, line code heart very cold. I do not know when the function is finished, killed the product to worship.

In the previous article, xiaobian brought you a lot of Vue combat skills, also got a lot of praise from everyone. In fact, in addition to the previous skills, we can do more to make our development process more smooth, better development experience, project performance to a higher level, how to do it, let’s take a look.

Read xiaobian recent popular Vue related articles, thank you dig friends and group friends support, Every Monday, be there or be square

Combat skills, Vue can also be written like this original praise 2600+

Absolute dry goods ~! With these Vue tips, you can leave work early and date the goddess with 1200 likes

High energy ahead, this is the latest wave of Vue combat skills, once used, amazing praise 1050+

Learn to use Vue JSX, a car full of Laoganma is your praise 650+

See earn! Rereading the vue2.0 style guide, I compiled these key rules and received 150+ likes

The content of this article is part of an out-of-the-box framework based on Vant packaging. The framework has internal integration including: The complete project directory structure, mobile adaptation, Vant loading on demand, Mock, static resource compression, AXIos secondary encapsulation, utility classes, CDN, code specification, EditorConfig, etc., can be downloaded and used without any basic configuration. Welcome to use it. Warehouse address github.com/snowzijun/v… , if you like, please give a star to xiaobian, xiaobian will continue to update.

Enable compression to make pages load faster

In our development, in order to facilitate debugging, we need to use source code for debugging, but in the production environment, we are looking for more is faster loading, better experience, at this time we will remove the space comments in the code, treat is obfuscated compression, just to make JS, CSS files become smaller, faster loading. But that’s not enough. We can do more than that.

Gzip is the most widely used file compression algorithm in the Web world, and most of the servers we use (such as Nginx) and clients (such as Chrome) already support this algorithm, so if we package a Vue project, You can directly compress all static resources into Gzip, which can greatly reduce the size of static resources and improve the browser loading speed. How to configure the Vue project?

addvue.config.jsfile

In a new Vue project, there is no vue.config.js file by default. First, you need to create a vue.config.js file in the project root directory and add the following code to the file

module.exports = {

}
Copy the code

The vue.config.js file will be used several times later in this article and will not be covered further.

configurationcompression-webpack-plugin

  • Install compression will – webpack – the plugin

    yarn add compression-webpack-plugin -D
    Copy the code
  • configuration

    Modify the vue.config.js file to the following code

    const CompressionWebpackPlugin = require('compression-webpack-plugin')
    const isProd = process.env.NODE_ENV === 'production'
    module.exports = {
      configureWebpack: config= > {
        if (isProd) {
     // Configure webPack compression  config.plugins.push(  new CompressionWebpackPlugin({  test: /\.js$|\.html$|\.css$/. // More than 4KB compression  threshold: 4096  })  )  }  } } Copy the code
  • Viewing the compression Effect

    After the preceding compression is configured, run the yarn build command, and you can find that a new file with suffix gz is added to the generated static file


    If you deploy your project to a gzip enabled server such as Nginx at this point, you can visit the browser and see that the browser downloaded the compressed file


Mobile adaptation

Currently, there are two popular adaptation methods on mobile terminal, one is to convert PX to REM, and the other is to convert PX to VW. When developing projects, I generally like to convert PX to VW, so how to configure it

The installationpostcss-px-to-viewport

First, you need to install the postCSs-px-to-viewPort plugin for your project

yarn add postcss-px-to-viewport -D
Copy the code

Configure mobile adaptation

Create a new file postcss.config.js under the project root directory and add the following code to the file

module.exports = {
  plugins: {
    autoprefixer: {},
    'postcss-px-to-viewport': {
      // The width of the window corresponds to the width of our design. Our company uses 375
 viewportWidth: 375. // The window height can be specified according to the width of 750 devices  // viewportHeight: 1334,  // Specifies the decimal number to convert 'px' to the window unit value  unitPrecision: 3. // Specify the window unit to convert to. Vw is recommended  viewportUnit: 'vw'. // Specify a class that is not converted to Windows units. It can be customized and added indefinitely. It is recommended to define one or two common class names  selectorBlackList: ['.ignore']. // less than or equal to '1px' does not convert to window units, you can also set to whatever value you want  minPixelValue: 1. // Allow conversion of 'px' in media queries  mediaQuery: false  }  } }  Copy the code

After the configuration is complete, restart the service and review the elements in the browser. You can see that the px originally written has been converted to vw


Mobile can’t debug, you need vConsole

Sometimes we develop mobile projects that work fine in the PC browser, but don’t work on the phone. This can be very confusing. How can I view logs on the phone, view interface requests and so on

The installationvConsole

VConsole is a plug-in developed by Tencent for debugging mobile terminal projects. You only need to run the following command to install vConsole

yarn add vConsole -S
Copy the code

For use in projects

In general, vConsole is only used in the development environment, not in the formal environment, so we only need to use it in the development environment. How to use it?

Open main.js and add the following code to it

// Use vConsole for debugging in the development environment
if (process.env.NODE_ENV === 'development') {
  const VConsole = require('vconsole')
  new VConsole()
}
Copy the code

When you start the project, a red button appears in the lower right corner of the system. Click on it and you’ll see a list of things you need to debug


Ignore the directory, letmomentBecome smaller

For those of you who have used Moment, you must know that the locale language package of Moment is very large, but our general project is only used in China, and there are not so many languages. Can we remove it? You need to use webpack.ignoReplugin.

In the vue.config.js file, you need to add the following code

const webpack = require('webpack')
module.exports = {
  chainWebpack: config= > {
    // Optimize moment to remove international content
    config
 .plugin('ignore')  // Ignore all files in /moment/locale  .use(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/))  } } Copy the code

/locale/’; /locale/’; /locale/’;

import moment from 'moment'
// Manually import the required language packs
import 'moment/locale/zh-cn';
// Specify the language to use
moment.locale('zh-cn');
Copy the code

Of course, I recommend using the lighter day.js for moment in your project

Production Environment Deletionconsole.log

The development environment will add a lot of console.log for debugging purposes, but if the console.log is submitted to the production environment, it will not only affect the code execution performance, but also may leak some core data. Therefore, we prefer to remove all console.log in the production environment.

Installing a plug-in

The babel-plugin-transform-remove-console plug-in is required

yarn add babel-plugin-transform-remove-console -D
Copy the code

configurationbabel.config.js

Open the babel.config.js file and add it to the file

// All production environments
const prodPlugin = []

if (process.env.NODE_ENV === 'production') {
  
// In a production environment, logs are automatically cleared but errors and warn are reserved  prodPlugin.push([  'transform-remove-console'. {  // Keep console.error and console.warn  exclude: ['error'.'warn']  }  ]) }  module.exports = {  plugins: [ . prodPlugin ] } Copy the code

openeslint.stylelint

See this one, some students can not stand a little want to exit, configuration this is not to find their own uncomfortable? In team development, it can be useful to have this in place, to make sure that everyone on the team is working to standards so that at least everyone doesn’t write code that is incomprehensible to each other (I suffer from non-standard code).

Full warehouse address github.com/snowzijun/v…

Install dependencies

Before you can configure lint, you need to install these plugins

  • @vue/cli-plugin-eslint
  • @vue/eslint-config-prettier
  • babel-eslint
  • eslint
  • eslint-plugin-babel
  • eslint-plugin-prettier
  • eslint-plugin-vue
  • husky
  • lint-staged
  • prettier
  • stylelint
  • stylelint-config-recess-order
  • stylelint-config-standard
  • stylelint-prettier
  • stylelint-scss

You also need to give vscode the following plug-ins

  • eslint
  • stylelint
  • Prettier – Code formatter

configurationvscode

Add the following code to vscode’s setting file

"eslint.enable":true."eslint.options": {
  "extensions": [    ".js".    ".vue". ".ts". ".tsx"  ]  },  "eslint.validate": [  "javascript". "javascriptreact". "typescript". "typescriptreact" ]. "css.validate": true. "scss.validate": true. "less.validate": true. "editor.codeActionsOnSave": {  "source.fixAll": true  }, Copy the code

configurationeslint

Start by adding.eslintrc.js and.eslintignore files under the project root directory

Add the following to the.eslintrc.js file

/ / mini version
module.exports = {
  root: true.  globals: {
    process: true
 },  parserOptions: {  parser: 'babel-eslint'. sourceType: 'module'  },  env: {  browser: true. node: true. es6: true  },  extends: ['plugin:vue/recommended'.'eslint:recommended']. plugins: ['babel'.'prettier']. rules: { // The verification rule is omitted here  } } Copy the code

Add the following code to the.eslintignore file

.DS_Store
node_modules
/dist

# local env files
.env.local .env.*.local  # Log files npm-debug.log* yarn-debug.log* yarn-error.log*  # Editor directories and files .idea .vscode *.suo *.ntvs* *.njsproj *.sln *.sw? Copy the code

After configuration, add it to the package.json script

"eslint": "vue-cli-service lint"
Copy the code

Then run yarn eslint to format the code, and of course vscode will also check the file when you save it

Configuration stylelint

Limit JS and Vue is not enough, also need to limit the following style, feel this is their own to their own infinite digging moves, but this thing with the more cool, a look

First, create the. Stylelintrc.js and. Stylelintignore files under the project root directory

Add the following contents to the.stylelintrc.js file

module.exports = {
  extends: ["stylelint-config-standard"."stylelint-config-recess-order"].  "plugins": [
    "stylelint-scss"
]. rules: {  // The verification rule is omitted  } } Copy the code

Stylelintignore The file content is the same as that of the. Eslintignore file

After configuration, add it to the package.json script

"stylelint": "stylelint src/**/*.{html,vue,css,sass,scss} --fix",
Copy the code

Then execute yarn stylelint to format the style, and of course vscode checks it once when you save the file

configurationhusky

In eslint, after stylelint is configured, vscode automatically validates the stylelint when writing code, but in case someone uses another editor without a plugin and submits unvalidated code to the repository, causing everyone’s code to go red, husky is used to validate the submitted code.

When Git commits code, a series of hook functions are triggered. Husky is a Git hooks tool. Lint-staged is a tool for running Linters on Git staging files. Why use it when you can only check your files that have already been modified before submitting code, it can be a waste of time to check all your files. So how do we configure it?

All you need to do is add the following code to the package.json file

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged".      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
 },  "lint-staged": {  "*.{js,vue}": [  "vue-cli-service lint". "git add -A" ]. "*.{html,vue,css,sass,scss}": [  "yarn stylelint"  ]  } Copy the code

Git commit -m ‘Commit description’ : esLint checks the stylelint code before committing

The warehouse address

All code in this article is uploaded to Github, the repository addressGithub.com/snowzijun/v…, this project has been used in many teams, you are invited to use together

conclusion

Don’t blow out your inspiration and your imagination; Don’t be a slave to your model. — Vincent Van Gogh


This article is formatted using MDNICE