Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vue CLI HTML and static resources


May 07, 2021 Vue CLI


Table of contents


Html

Index file

public/index.html file is a template that will be processed by html-webpack-plugin. D uring the build process, resource links are automatically injected. In addition, the Vue CLI automatically injects resource hints (preload/prefetch, manifest, and icon links (when PWA plug-ins are used) and resource links to JavaScript and CSS files processed during the build process.

Interpolation

Because index files are used as templates, you can insert content using the lodash template syntax:

  • the use of value %/value for non-escape interpolation;
  • lt;%-VALUE %-gt; used to do HTML escape interpolation;
  • Used to describe JavaScript process control.

In addition to the default values exposed by html-webpack-plugin, all client environment variables can also be used directly. For example, BASE_URL use of this:

<link rel="icon" href="<%= BASE_URL %>favicon.ico">

More information can be found at:

Preload

"preload" is a resource hint that specifies the resources that will be used as soon as the page loads, so during the page load process, we want to preload as early as possible before the browser starts rendering the main body.

By default, a Vue CLI app automatically generates preload prompts for all files required for initial rendering.

These prompts are @vue/preload-webpack-plugin and can be modified and deleted through chainWebpack's config .plugin ('preload').

Prefetch

"prefetch" is a resource hint that tells the browser to use its free time to get content that users might access in the future in advance after the page loads.

By default, a Vue CLI app automatically generates prefetch prompts for all JavaScript files generated as async chunk (a product of dynamic import() on-demand code splitting).

These prompts are @vue/preload-webpack-plugin and can be modified and deleted via chainWebpack's config .plugin ('prefetch').

Example:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    // 移除 prefetch 插件
    config.plugins.delete('prefetch')

    // 或者
    // 修改它的选项:
    config.plugin('prefetch').tap(options => {
      options[0].fileBlacklist = options[0].fileBlacklist || []
      options[0].fileBlacklist.push(/myasyncRoute(.)+?\.js$/)
      return options
    })
  }
}

When the prefetch plug-in is disabled, you can manually select the code chunks to get in advance from the inline comments of the webpack:

import(/* webpackPrefetch: true */ './someAsyncComponent.vue')

The runtime of the webpack injects a prefetch link after the parent chunk is loaded.

Tips

Prefetch links consume bandwidth. If your application is large and has a lot of async chunk, and the user is primarily using a mobile side that is more bandwidth sensitive, you may need to turn off the prefetch link and manually select the code chunks to get in advance.

Index is not generated

When using the Vue CLI based on an existing backend, you may not need to generate index .html so that the resulting resources can be used for a page rendered on the service side. At this point, you can add the following code .js vue.config:

// vue.config.js
module.exports = {
  // 去掉文件名中的 hash
  filenameHashing: false,
  // 删除 HTML 相关的 webpack 插件
  chainWebpack: config => {
    config.plugins.delete('html')
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')
  }
}

However, this is not very recommended because:

  • Hard-coded file names are not conducive to efficient cache control.
  • Hard-coded file names also don't work well with code-splitting (code segmentation), because you can't generate additional JavaScript files with changing file names.
  • Hard-coded file names do not work in modern mode.

You should consider swaping the indexPath option to use the generated HTML as a view template for a service-side framework.

Build a multi-page app

Not every app needs to be a single-page app. T he Vue CLI supports building a multi-page app .js pages option in vue.config. Well-built apps will efficiently share common chunks between different portals for optimal loading performance.

Handle static resources

Static resources can be processed in two ways:

  • It is imported in JavaScript or referenced by relative path in template/CSS. Such references are handled by webpack.
  • Placed in the public directory or referenced by an absolute path. Such resources will be copied directly without being processed by webpack.

Import from a relative path

When you reference a static resource in a JavaScript, CSS, or .vue file using a relative path (which must begin with . ), the resource is included in the dependency diagram that enters the webpack. During its compilation process, all resource URLs such as .lt;img src=@import...",""

For example, url (./image.png) is translated as require ('./image.png') and:

<img src="./image.png">

will be compiled to:

h('img', { attrs: { src: require('./image.png') }})

Internally, we determine the final file path by using the version hash value and the correct common base path, and then using url-loader to inline resources less than 4kb to reduce the number of HTTP requests.

You can adjust the size limit of inline files with chainWebpack. For example, the following code sets its limit to 10kb:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('images')
        .use('url-loader')
          .loader('url-loader')
          .tap(options => Object.assign(options, { limit: 10240 }))
  }
}

URL conversion rules

  • If the URL is an absolute path (for example/ images/foo.png), it will remain unchanged.
  • If the URL is in . At the beginning, it is interpreted as a relative module request and parsed based on the directory structure in your file system.
  • If the URL starts with , anything that follows is resolved as a module request. T his means that you can even refer to the resources in the Node module: .lt;img src="-some-npm-package/foo.png"
  • If the URL starts with , it is also resolved as a module request. I t is useful because the Vue CLI defaults to an alias that points to the .lt;projectRoot>/src. (Only in templates)

Public folder

Any static resources placed in the public folder are simply copied without going through the webpack. You need to refer to them through absolute paths.

Note that we recommend importing resources as part of your module dependency diagram, so that they can be processed by webpack and benefit from:

  • Scripts and style sheets are compressed and packaged together to avoid additional network requests.
  • File loss results in a 404 error when the file is compiled directly, rather than on the user side.
  • The resulting file name contains a content hash, so you don't have to worry about the browser caching their older versions.

The public directory provides an emergency, and when you reference it through an absolute path, be aware of where your app will be deployed. If your app is not deployed at the root of the domain name, you need to configure the publicPath prefix for your URL:

  • In public/index.html or other HTML files that are used as templates by html-webpack-plugin.ico BASE_URL, you need to set the link prefix by BASE_URL setting up the link prefix:
  • In the template, you first need to pass the underlying URL to your component: data (.png process.env.BASE_URL) .

When to use the public folder

  • You need to specify the name of a file in the build output.
  • You have thousands of pictures and need to refer to their paths dynamically.
  • Some libraries may not be compatible with webpack, so you have no choice but to introduce them with a separate label.