Configure the preload plugin when Vue Cli builds a multi-page application

Vue CLI can be configured under the vue.config.js file pagesfor multi-entry packaging configuration to achieve multi-page application development.

If you want to modify the plug-in configuration in multi-page mode, some problems may occur, and the common one is preload-webpack-pluginplug-in.

Configuration example:

// vue.config.js
module.exports = {
    
    
  pages: {
    
    
    pc: {
    
    /*...*/},
    h5: {
    
    /*...*/}
  },
  chainWebpack(config) {
    
    
    config.plugin("preload").tap(() => [
      {
    
    
        rel: "preload",
        //...
      }
    ]);
  },
  // ...
}

When packaging like this, an error will be reported:

Error: Cannot call .tap() on a plugin that has not yet been defined. Call plugin('preload').use(<Plugin>) first.

The reason is config.plugin("preload")that did not get preloada plugin instance named .

Official tip:

When building in multi-page mode, the webpack configuration will contain different plugins (there will be multiple instances of html-webpack-pluginand preload-webpack-plugin). If you try to modify the options of these plugins, please make sure to run them vue inspect.

Deleted the plug-in configuration, and used to vue inspectview the webpack configuration. In the original multi-page mode, Vue Cli was configured with the same number of plug-in configurations as the page:

{
    
    
  plugins: [
    //...
    // 2 个 html-webpack-plugin 配置
    /* config.plugin('html-h5') */
    new HtmlWebpackPlugin(/*...*/),
    /* config.plugin('html-pc') */
    new HtmlWebpackPlugin(/*...*/)
    
    // 2 个 preload-webpack-plugin 的 preload 配置
    /* config.plugin('preload-h5') */
    new PreloadPlugin({
    
    rel: 'preload',/*...*/})
    /* config.plugin('preload-pc') */
    new PreloadPlugin({
    
    rel: 'preload',/*...*/})

    // 2 个 preload-webpack-plugin 的 prefetch 配置
    /* config.plugin('preload-h5') */
    new PreloadPlugin({
    
    rel: 'prefetch',/*...*/})
    /* config.plugin('preload-pc') */
    new PreloadPlugin({
    
    rel: 'prefetch',/*...*/})
  ]
}

The comments also indicate that the identifiers for obtaining plug-in instances are preload-h5and preload-pc, not preload.

So just configure with the new id:

// vue.config.js
const pages = {
    
    
    pc: {
    
    /*...*/},
    h5: {
    
    /*...*/}
}
module.exports = {
    
    
  pages: pages,
  chainWebpack(config) {
    
    
    Objects.keys(pages).forEach(name => {
    
    
      config.plugin(`preload-${
      
      name}`).tap(() => [
        {
    
    
          rel: "preload",
          // ...
        }
      })
    ]);
  },
  // ...
}

Guess you like

Origin blog.csdn.net/u012961419/article/details/120134210#comments_26910336