1. Origin of the article

I am very busy with my work recently, so I am here to make up for it. Although the official version of VUe3 has appeared (now using the latest scaffolding to create a project vUE version is 3.0), but now the ecology is not perfect, the other friends of The Dig Gold have done a lot of vuE3 sharing, I will not do here, of course, you can go to kangkang it 👉 (vue3). Today’s main members are still VUE2. After all, vuE2 is still popular now. This article mainly shares the pre-work I have done before writing the project, on the one hand, it is convenient for you to have a more familiar understanding of some optimized configurations, and on the other hand, you can copy relevant configurations. Three to my memory is not very good follow-up need can come over to copy their own configuration 😁, first of all, I have personally tested each drop.

2 Here we go

2.1 Getting Started

If you use sass, please make sure to select Dart-sass. It is easy to install and use node-sass. If you use sass, please choose Dart-sass. The only difference I remember is that style penetration dart-sass has to be written like this

<style lang="scss" scoped>

/ * 1 * /

.a{

 ::v-deep .b { 

/ *... * /

 }



The usage / * 2 * /

.a ::v-deep .b {

/ *... * /

}

</style>

Copy the code

2.2 ESLint can be seen here

To tell you the truth, I was quite terrified of Eslint at first, writing a bunch of red warnings every time, and then realizing, well, how nice it was to configure VsCode to automatically format itself according to the relevant Eslint configuration. Of course, now the NPM script for new Vue projects also has a lint option, This is the default configuration, but having to execute Lint every time before executing it is cumbersome, plus we have internal custom rules, so we still have to do it ourselves

  • First, we need to set up a.eslintrc.js file in the project root directory with all the rules in it.just because I dont love you with all the rules, doesnt mean I dont love you with all the rules, just because I dont love you with all the rules, doesnt mean I dont love you with all the rules Of course, more detailed configuration instructions can be found here at 👉 ESLint configuration instructions

  • Create an 👉. Eslintignore file and set esLint to ignore files/folders

  • You need to install the VsCode plug-in (eslint, prettier), then set setting.json in the workspace. After all, every project has different rules), add the following configuration

{

  "files.autoSave""onFocusChange".

  "editor.codeActionsOnSave": {

    "source.fixAll.eslint"true

  }

}

Copy the code

And then you can restart the compiler, you can start the project try, literally in js, add a semicolon (custom rules set a code at the rear there is no semicolon, should be more than one that I don’t like the semicolon), save or make the mouse in the build area loses focus, you will find that automatically in addition to the semicolon, rules, of course, much more than this, There is also a configuration for.vue, but you don’t need to worry about it in the future, you can just press CTRL+S or lose focus save OK, so your code will be clean, you won’t have a grain of sand to make your eyes hot

  • You may encounter situations where you cannot create.eslintrc.js in VsCode. You can create the.eslintrc.js file in your project folder instead of VsCode

2.3 Configuring Environment Variables and Modes

For 🌰, believe a lot of friend’s request to the address of the API should be two, more or less, an interface is test used in the development process, is a packaging line of formal interface, so we can better when packaging will forget to replace what interface, while most of the time only need to Nginx reverse proxy, but will appear on this problem, Hypothesis testing request to http://127.0.0.1:4000/a, the official request address is http://127.0.0.1:4000/a/b, configure Nginx proxy only http://127.0.0.1:4000/a, the official environment GG, Can not request B ah, of course, this is not professional situation, professional are no problem, this time to deal with the encounter not professional colleagues how to solve the problem. It’s just 🌰, but you can do a lot of things by configuring environment variables and patterns

  • First we need to know how 👉 environment variables and patterns are understood and how to configure and pay attention to what details
  • Create several env files (you can create as many as you want)
.env.dev            Only loaded in the development environment

    # Here's what's in.env.dev

    NODE_ENV = development    # specify the execution environment

    ENV = 'dev'  # specify the mode for executing the script

    VUE_APP_BASE_API = 'http://127.0.0.1:4000/a'  # specify the interface to request

    

.env.build_test     Only loaded in the packaged test environment

    # Here is the contents of.env.build_test

    NODE_ENV = production

    ENV = 'build_test'

    VUE_APP_BASE_API = 'http://127.0.0.1:4000/a'

    

.env.build_prod     Only the packaged formal environment is loaded

    # Here is the contents of.env.build_prod

    NODE_ENV = production

    ENV = 'build_prod'

    VUE_APP_BASE_API = 'http://127.0.0.1:4000/a/b'

Copy the code
  • Configure our package.json execution script
 "scripts": {

    "serve""vue-cli-service serve --mode dev".

    "build:test""vue-cli-service build --mode build_test".

    "build:prod""vue-cli-service build --mode build_prod"

  }

Copy the code

When we do yarn serve/NPM run serve we will use the configuration in.env.dev, as well as the others, and then we can configure the request prefix in AXIos or fetch. Please note that Using environment variables (such as our request address) in the client-side code, only variables starting with VUE_APP_ can be read, which is explicitly documented

import axios from "axios";

const service = axios.create({

// VUE_APP_BASE_API of the. Env * file is currently available here

  baseURL: process.env.VUE_APP_BASE_API

});

Copy the code

2.4 Configuring Vue.config. js Do some configuration and optimization

The only 4 configured for scaffolding and scaffolding, no 2, for this section, to be honest, a lot of friend to share is not very detailed, most of time only to say with what plug-ins, but didn’t write specific code, how can this plugin to use, in which position, to say nothing at all, for beginners is not very convenient

  • Create a vue.config.js file in the project root directory and you can do the configuration in it. Of course, this is a simple configuration
module.exports = {

/ * *

* If you plan to deploy sites under subpaths, you need to set publicPath,

* For example, GitHub Pages. If you plan to will be deployed to the web site, https://foo.github.io/bar/,

* Then publicPath should be set to "/ bar/".

* In most cases, please use'/'!

* details: https://cli.vuejs.org/config/#publicpath

  * /

  publicPath: ". /"// Static resource access

  outputDir: "dist"// Package the output path

  productionSourceMap: false, // Whether generate SourceMap file location error (files will be too many affect the performance recommended cancel)

// Configure the proxy of the development environment to resolve the cross-domain situation. Note that devServer is only valid in the development environment. The cross-domain situation that occurs after packaging can be resolved by the backend and nginx reverse proxy

  devServer: {

    port: 4000,

    proxy: {

      "/": {

        target: process.env.VUE_APP_BASE_API,

        pathRewrite: {

          "^ /""/"

        }

      }

    }

  }

}

Copy the code

2.4.1 Perform configurations in configureWebpack and chainWebpack

Of course, for the difference between the two and the mode, you can go to 👉 to check the official document.

  • First of all, for common paths, I think you don’t want to see components that are deep enough to use a resource appear… /.. /.. /utils/index.js is the case, so we can configure the alias in configureWebpack, and then access @/utils/index.js instead, so to say, ‘.. /.. /.. / === @’
// Exports in module.exports

configureWebpack:{

  resolve: {

    alias: {

      The '@': path.join(__dirname, 'src')

    }

  }

}

Copy the code
  • Many people are not used to debug. Most of them have a lot of consoles. If we want to solve the problem of eliminating the console in the project after packaging, we should not find and delete the console one by one. So we’re going to use our plugin terser-webpack-plugin so you can’t see console online
// yarn add terser-webpack-plugin -D

const TerserPlugin = require('terser-webpack-plugin');



// Exports in module.exports

configureWebpack:{

  optimization: {

      minimizer: [

        new TerserPlugin({

          terserOptions: {

            ecma: undefined,

            warnings: false.

            parse: {},

            compress: {

              drop_console: true.

              drop_debugger: false.

              pure_funcs: ['console.log'] // Remove console

            }

          }

        })

      ]

   }

}

Copy the code
  • Gzip compression is probably familiar, but in nginx configuration is far from enough, we also have to add this to our own projects, packaging when the project Gzip compression, with nginx Gzip, online environment greatly improve the load speed of resources. So here’s our second plug-in, compression-webpack-plugin, where we need to decide what environment to use it in
// yarn add compression-webpack-plugin -D

const CompressionPlugin = require('compression-webpack-plugin');



const plugins = []

if(process.env.NODE_ENV === 'production') {

  plugins.push(new CompressionPlugin({

      test: / \. Js $| \. HTML $| \. CSS /, / / to compress recognition to the file

Threshold: 10240, // Compress data exceeding 10K

      deleteOriginalAssets: false// Do not delete the source file, if nginx enabled gzip can be deleted

  }))

}





// Exports in module.exports

configureWebpack:{

// introduce here

  plugins:plugins

}

Copy the code

Seriously, this plugin is quite useful. Indeed, gzip significantly improves the loading speed of resources. How to say, I waited 40 seconds for the first screen to appear on the company’s tudou server, which is used as the test environment, but it only took 9s to open it

  • Next we’ll do a more granular configuration in the chainWebpack and paste the configuration below
chainWebpack(config) {

// To improve the speed of the first screen, it is recommended to turn on preloading. This sentence reduces the loading speed of the above 9s to 7s, although it is not high, but the mosquito is still meat

    config.plugin('preload').tap(() => [

      {

        rel: 'preload'.

        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],

        include: 'initial'

      }

    ])

// When the page is large, it will result in too many meaningless requests

    config.plugins.delete('prefetch')

    

    config

.when(process.env.NODE_ENV ! = ='development'.

        config => {

// Package only third-party dependencies

          config

            .plugin('ScriptExtHtmlWebpackPlugin')

            .after('html')

            .use('script-ext-html-webpack-plugin'[{

inline: /runtime\.. *\.js$/

            }])

            .end()

          config

// With the optimization.splitchunks configuration option, duplicate dependency modules can be removed. Note that the plug-in reduces the size of the code by separating some third-party modules into separate blocks. You can see the size of the blocks in the Dist file

            .optimization.splitChunks({

              chunks: 'all'.

              cacheGroups: {

                libs: {

                  name: 'chunk-libs'.

                  test: /[\\/]node_modules[\\/]/,

                  priority: 10,

                  chunks: 'initial'

                },

                antdUI: {

                  name: 'chunk-antdUI'// I use antDV to cut antDV into a package

                  priority: 20,

                  test: /[\\/]node_modules[\\/]_? ant-design-vue(.*)/

                }

              }

            })

            

          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk

          config.optimization.runtimeChunk('single')

        }

      )

  }

Copy the code

The above is some of our packaging optimization of VUE, to be honest, this place is bumpy, after all, I am not familiar with the specific configuration of Webpack, only remember the concept, plus a lot of articles to write relatively shallow, really start to report errors everywhere, but fortunately all solved, but also learned a lot

2.5 Optimize the directory structure and file naming

We should keep in mind that directory structure is a view folder when we see views, utils when we see a tool library folder, and we should call it something that makes sense. If you’re running out of words, Let 👉 Codelf help you pick your name

If you want to delete node_modules from Windows 10, you can delete them using rimraf. If you want to delete node_modules from Windows 10, you can delete them using Rimraf. Run rimraf node_modules in the root directory and delete it immediately. This can also be written in the package.json execution script

3 The end is over

This article focuses on some preparations before formally writing the project. For the optimization of writing code, you can refer to the article of other partners. Although the article is not very in-depth, I think it is very clear and can let more new partners understand it

Finally, thank you for your taste. The code I have prepared is posted below, which contains some reference codes and some configured vue.config.js. If you want to start a new project, this is a very good choice

  • 👉The project address

Be the best time manager, master of your time. – I said