This code is based on Webpack4.

Objective: subcontracting, the purpose is to cooperate with browser cache, hit the cache, no need to download, improve the experience.

To pack or not to pack refers to two ways:

Package: splitChunks;

Unpacked: externals;

externals

Usage:

Take, for example, the VUE three-piece suite.

// webpack.config.js
module.exports = {
  externals: { // Configure the package that does not participate in packaging here
    vue: 'Vue'.'vue-router': 'VueRouter'.vuex: 'Vuex',}};Copy the code

In the corresponding index.html, the dependency needs to be introduced with

<script src=https://cdn.jsdelivr.net/combine/npm/[email protected],npm/[email protected],npm/[email protected]></script>
Copy the code

When you write code, just import it normally, and WebPack will help you link up the global dependencies, so you don’t have to worry too much about it.

HtmlWebpackPlugin can be used with HtmlWebpackPlugin, realize the local start dev server using node_modules dependency, package

Expected effect:

  1. Dependencies directly introduced by script tags, combined with the browser’s caching mechanism, can achieve cross-project and cross-version sharing effect, improve user loading speed.
  2. Packaging speed has been improved (less js files are packed).

splitChunks

Usage:

It is still a vUE three-piece package, packaged separately.

This format forces vue, vuex, and vue-router to be packaged separately into a file. The result is chunk-hahahaha. Afd6a08b.js.

Again, the user doesn’t have to do anything, just write the code.

// webpack.config.js
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all'.// include all types of chunks
      cacheGroups: {
        hahahaha: {
          name: 'chunk-hahahaha'.test: /[\\/]node_modules[\\/]((vue)|(vuex)|(vue-router))[\\/]/.// VUE is not packaged
          priority: 10.chunks: 'initial'.// only package third parties that are initially dependent},},},},};Copy the code

Expected effect:

By limiting the contents of the chunk, the packaged file name will remain the same even if the version remains the same (the content remains the same, hash remains the same).

In this way, local caches can be used after the release of a new version, in conjunction with the mechanism for negotiating caches. (It’s a shame that it can’t be shared across projects)

Note that although the file name remains the same, the last-modified time changes after the release should be considered. In this case, the backend should control the negotiation cache policy, or note that the file with the same name —- should not be overwritten during the release.