SoFunction
Updated on 2025-04-04

Building element backend framework optimization from 0 to 1 (packaging optimization)

Preface

hello, we're seeing each other again~~hehehe. This time, we will mainly talk about the issue of packaging optimization. A vue project must go through the packaging process from development to launch. Whether a project is packaged or not determines the running speed and user experience of your project. This time, it is mainly optimized for JS configuration. Project gallery

Development environment and production environment

The configuration of the development environment and the production environment is also an indispensable part of development. This project is developed by vue-cli3. vue-cli3 deeply integrates webpack. If you are not familiar with vue-cli3, you can first go to the official website to check the relevant configuration.

Development Environment

Create a new file in the project root directory to indicate that it is a development environment.

 VUE_APP_CURRENTMODE ="development" //Current environment VUE_APP_LOGOUT_URL="http://localhost:3000/" //Development environment address

Production environment

Create a new file in the project root directory to indicate that it is a production environment.

 VUE_APP_CURRENTMODE ="development" //Current environment VUE_APP_LOGOUT_URL="xxx" //The address of the production environment

Of course, you can also create a test environment yourself. It can also be configured like the above.

Environmental application

So how do we use it next? I have to mention here that the two commands served and build are in it. In fact, the corresponding commands are vue-cli-service serving --mode development, vue-cli-service build --mode production. If you want to use development environment variables in the build command, you can add them.

"dev-build": "vue-cli-service build --mode development"

Next, use it.

 ('define').tap(args => {
   args[0][''].VUE_APP_LOGOUT_URL = (.VUE_APP_LOGOUT_URL)
   (args[0])
   return args;
 });

It is necessary to say here that this code is written under the chainWebpack configuration item. This code actually uses two webpack plugins, webpack-chain, to allow configuration of chain operations, as well.

  1. webpack-chain: Try to create and modify webpack configurations by providing chainable or downstream APIs. learn more
  2. : Its function is to define global constants, which are constants. That is, the global constant defined by the module, then you cannot change it. That is to say, I have defined a .VUE_APP_LOGOUT_URL constant, which can be used under the src folder. learn more

Code splitting

First of all, what problems will arise when the third-party package we introduced are packaged together with our business code?

As the name suggests, our business code changes more frequently, while the third-party packages we introduce basically will not change. The browser will have a cache, and files without changes will be read directly from the cache, which indirectly optimizes the website's access speed.

Next configuration,

Split third-party library

 //Code segmentation (true);
 ({
  chunks: 'all',
  cacheGroup:{
  // vue2-editor makes a package separately   vueEdior: {
   name: 'vueEdior',
   test: /[\\/]node_modules[\\/]vue2-editor[\\/]/,
   priority: 10 // Priority must be greater than vendors, otherwise it will be packaged into vendors   },
   //The remaining third-party packages are transferred to vendor   vendors: {
   test: /[\\/]node_modules[\\/]/,
   priority: -10
   }
  }
 })

Split common files

Components are an important part of the vue project. A considerable number of components can be publicly available and introduced in different files, so we can directly split this part of the public components.

 (true);
 ({
  chunks: 'all',
  cacheGroup:{
   vueEdior: {
   name: 'vueEdior',
   test: /[\\/]node_modules[\\/]vue2-editor[\\/]/,
   priority: 10 // Priority must be greater than vendors, otherwise it will be packaged into vendors   },
   public: {
   name: 'public',
   test: resolve('src/components'),
   minSize: 0, //Indicates the minimum module size before compression, the default value is 30kb   minChunks: 2, // Minimum number of common times   priority: 5, // Priority   reuseExistingChunk: true // Public module must be turned on   },
   //The remaining third-party packages are transferred to vendor   vendors: {
   test: /[\\/]node_modules[\\/]/,
   priority: -10
   }
  }
 })

After packaging, you will find that dist/static/js, and there is an additional vueEditor and public file, which means that the division is completed.

Map file processing and alias settings (alias)

map file

We can further optimize and generate map files by default for packaging, resulting in the size of the package being too large. At this time, we need to set a property to close it.

productionSourceMap: false

Alias ​​Settings

The advantage of using alias is that it does not need to be searched one by one, but directly locks the position, thereby reducing file search time.

 //Set an alias 
  .set('@', resolve('src'))
  .set('@api', resolve('src/api/api'))//Interface address  .set('@assets', resolve('src/assets'))

gzip compression and console plugin

If all the above methods are written and the files are still too large, you have to consider code compression and removing the console plug-in. It can be said that in order to optimize the project, you "do everything you can do".

gzip compression

First install start installation

cnpm install compression-webpack-plugin --save-dev

Then configure it in configureWebpack

 const CompressionWebpackPlugin = require('compression-webpack-plugin')
 new CompressionWebpackPlugin({
  filename: '[path].gz[query]',
  algorithm: 'gzip',
  test: new RegExp(
   '\\.(' +
   ['js', 'css'].join('|') +
   ')$',
  ),
  threshold: 10240,
  minRatio: 0.8,
  }),

It is worth noting that the gzip compressed files need to be supported by the backend. If the backend does not support them, the project still loads the uncompressed files.

Go to console plugin

Install first

cnpm install uglifyjs-webpack-plugin --save-dev

Then configure it in configureWebpack

 const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
 new UglifyJsPlugin({
  uglifyOptions: {
   compress: {
   warnings: false,
   drop_debugger: true,
   drop_console: true,
   },
  },
  sourceMap: false,
  parallel: true,
  }),

cdn introduction

Some students say that the backend does not support gzip compression loading, so what should I do? That’s all cold dishes~~~.
Here I will introduce you to a method of introducing cdn. Some third-party plug-ins are too large, which is quite large after being subcontracted separately. At this time, you can consider using cdn to introduce files.

Introducing cdn without plug-in

First of all, we don't let webpack package files imported with cdn

   

 //For some libraries that are not changed frequently, they can be introduced through cdn, and webpack does not package them let externals = {
  'vue': 'Vue',
  'axios': 'axios',
  'element-ui': 'ELEMENT',
  'vue-router': 'VueRouter',
  'vuex': 'Vuex',
  'echarts': 'echarts',
  'vue2-editor': 'VueEditor'
 }

Then configure cdn

 

 const cdn = {
  css: [
  //element-ui css
  '/element-ui/lib/theme-chalk/'
  ],
  js: [
  //vue
  '/[email protected]/dist/',
  //axios
  '/axios/0.19.0-beta.1/',
  //vuex
  '/[email protected]/dist/',
  //vue-router
  '/[email protected]/dist/',
  //element
  '/[email protected]/lib/',
  //echarts
  '/npm/[email protected]/dist/',
  //vue2-editor
  "/[email protected]/dist/"
  ]
 }

Next, configure it in chainWebpack

 .VUE_APP_CURRENTMODE === 'production') {
  (externals)//Ignore the package  ('html')
  .tap(args => {
   args[0].cdn = cdn;
   return args
  })
 }

What needs to be explained here is that ('html') actually uses the html-webpack-plugin plugin to mount the cdn object in its instantiated options, and then read the relevant cdn through the ejs template syntax.

Immediately afterwards we need to read the relevant cdn in public/

 <% if (.VUE_APP_CURRENTMODE === 'production') { %>
  <% for(var css of ) { %>
  <link rel="stylesheet" href="<%=css%>" rel="external nofollow" as="style">
  <% } %>
  <% for(var js of ) { %>
  <script src="<%=js%>"></script>
  <% } %>
 <% } %>

At this point, the introduction of cdn is completed

Plugins introduce cdn

Since manually introducing cdn is too troublesome and worrying about version changes, you need to manually change it every time. Therefore, for a better development experience, an automatic matching cdn plug-in, webpack-cdn-plugin, was introduced. Next start the installation

cnpm install webpack-cdn-plugin --save

Instantiate plug-ins

const cdnPlugin = require('webpack-cdn-plugin')

Next start quoting in configureWebpack

 new cdnPlugin({
  modules: [
   { name: 'vue', var: 'Vue', path: 'dist/' },
   { name: 'axios', var: 'axios', path: 'dist/' },
   { name: 'vuex', var: 'Vuex', path: 'dist/' },
   { name: 'element-ui', var: 'ELEMENT', path: 'lib/', style: 'lib/theme-chalk/' },
   { name: 'echarts', var: 'echarts', path: 'dist/' },
   { name: 'vue2-editor', var: 'VueEditor', path: 'dist/' },
   { name: 'vue-router', var: 'VueRouter', path: 'dist/' },
  ],
  publicPath: '/node_modules'
  })
  • name: plugin name
  • var: The name instantiated in the project
  • path: path name
  • style:css path name

For more information, please refer toOfficial Documentation

Overall, the introduction of third-party CDN can indeed bring good results, but it may be unstable. Therefore, it is recommended that you apply for an exclusive CDN domain name in actual development and upload the library you want to use on the website directly.

Conclusion

That’s all for this issue’s packaging optimization! I feel like there is a lot of nonsense. Haha~~, finally, thank you for reading. If you have any questions or errors, please correct them in time.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.