current position:Home>Learn about the use of webpcak in Vue

Learn about the use of webpcak in Vue

2021-08-27 00:14:51 yuobey

One , know webpack

Webpack  It's a packaging modularity JavaScript Tools for , stay Webpack All the documents in are modules , adopt Loader Convert files , adopt Plugin Inject the hook , Finally, output the file composed of multiple modules .Webpack Focus on building modular projects .

In fact, it's a packing tool that's a little overqualified , I personally think it's a set of front-end Automation 、 modularization 、 A scalable system that integrates components , You can do a series of configuration and installation according to your own needs , Finally you need to achieve the functions and packaging output .

image.png All the documents :JavaScript、CSS、SCSS、 picture 、 Templates , stay Webpack They're all modules in their eyes , The advantage of this is that it can clearly describe the dependencies between the modules , To facilitate Webpack Combine and package modules . after Webpack To deal with , Finally, it will output the static resources that the browser can use .

stay Vue In the project ,webpack It's important , For example, pack and compress 、 Load asynchronously 、 Modular management and so on .

Two ,webpack Use

1. vue-cli 2.x And vue-cli 3.x The difference of

If used vue-cli 2.x, Then you should know that the directory it builds will contain the corresponding webpack The configuration file , But in vue-cli 3.x But you don't see one about webpack Configuration file for ,cli 3.x Provides an out of the box mode , That is, you don't need to configure webpack You can run the project , And it provides a vue.config.js Files to satisfy the developer's encapsulation of webpack Extension and modification of default configuration . Pictured (cli-3.xx To configure ):

image.png

cli 2.xx Configuration file diagram

image.png

The comparison shows that cli 3.x Remove all kinds of complicated configuration files , Unified into a separate file, allowing developers to expand the configuration of the project alone .

2. vue.config.js Configuration of

Through the comparison above , We can see clearly vue.config.js Configuration item structure of , The built project does not have this configuration file by default , Then you need to create it manually at the root . The functions and uses of common configuration items :

(1). baseurl

We go through vue-cli 3.x Successfully built and opened in browser  http://localhost:8080/  Show the front page of the project . If you want to add a secondary directory to the project address now , such as :http://localhost:8080/vue/, So we need to vue.config.js Internal configuration baseurl This one ( from Vue CLI 3.3 It has been abandoned , Please use publicPath):

// vue.config.js
module.exports = {
    ...
    
    baseUrl: 'vue',
    
    ...
}
 Copy code 

What has changed is webpack In profile output Of  publicPath  term , At this time, when you restart the terminal and open the page again, our home page url It's going to take the form of a secondary directory .

(2). outputDir

If you want to package and output the built files to output Under the folder ( The default is dist Folder ), You can configure :

// vue.config.js
module.exports = {
   ...
   
   outputDir: 'dist', // Default dist
   
   ...
}
 Copy code 

And then run the command  npm run build  For packaging output , You will find that projects and directories will create dist Folder , It's actually changed webpack Configuration in progress output Under the  path  term , Modified the output path of the file .

(3).productionSourceMap

This configuration item is used to set whether to build a build for the production environment source map, In general, in order to quickly locate the error information in the production environment , We'll all turn on source map:

// vue.config.js
module.exports = {
    ...
    productionSourceMap: true,
    ...
}
 Copy code 

The configuration will change webpack in  devtool  The value of the item  source-map.

Turn on source map after , We package the output file with js Corresponding .map file , Its use can refer to :JavaScript Source Map Detailed explanation

(4).  devServer

vue.config.js It also provides devServer Item is used to configure webpack-dev-server act , So that we can configure the local server accordingly , We run... On the command line  npm run serve  The corresponding order  vue-cli-service serve  In fact, it is based on webpack-dev-server Open a local server , The common configuration parameters are as follows :

// vue.config.js
module.exports = {
    ...
    
    devServer: {
        open: true, //  Do you want to open the browser page automatically 
        host: '0.0.0.0', //  Specify to use a  host. The default is  localhost
        port: 8080, //  Port address 
        https: false, //  Use https Provide services 
        // proxy: null, // string | Object  Agent settings   Generally handle cross domain request forwarding 
        proxy: {
          '/repos': { // Match to  /repos  character string   Auto forward to target Address 
            target: 'https://api.github.com', // Forwarding address 
            changeOrigin: true
            // pathRewrite: {'^/api': ''} // Rewrite address 
          }
        },
        //  Provides the ability to execute custom middleware before other middleware inside the server 
        before: app => {
          // `app`  It's a  express  example 
        }
    }
    
    ...
}
 Copy code 

(5).  chainWebpack

chainWebpack Configuration items allow us more granular control webpack Internal configuration , It integrates  webpack-chain  This plugin , This plug-in allows us to use chain operations to modify the configuration , such as :

//  Used to do the corresponding merge processing 
const merge = require('webpack-merge');

module.exports = {
    ...
    
  chainWebpack: (config) => {
    config.module.rules.delete('svg') //  a key : Delete the process in the default configuration svg,
    config.resolve.alias
      .set('@', resolve('src'))
      .set('~lib', resolve('src/common'))
      .set('~com', resolve('src/components'))
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons')) //  Handle svg Catalog 
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
      // To configure  rules  The rule is  url-loader  value 
    config.module
        .rule('images')
        .use('url-loader')
        .tap(options =>
            merge(options, {
              limit: 5120,
            })
        )
  },
    ...
}
 Copy code 

We can modify the above operations successfully webpack in module Configuration in item rules The rule is url-loader value , Put it limit The limit was changed to 5M, Configuration rules by icons Of svg-sprite-loader value Use The modified webpack The configuration code is as follows :

{
    ...
    
    module: {
        rules: [
            {   
                /* config.module.rule('images') */
                test: /.(png|jpe?g|gif|webp)(?.*)?$/,
                use: [
                    /* config.module.rule('images').use('url-loader') */
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 5120,
                            name: 'img/[name].[hash:8].[ext]'
                        }
                    }
                ]
            }
        ]
    }
    
    ...
}
 Copy code 

What we need to pay attention to here is that we use webpack-merge This plugin , This plug-in is used to do webpack Configuration merge , such options Other values below will not be overridden or changed . About webpack-chain The use of can refer to its github Official address :github.com/mozilla-neu…, It provides operations similar to JavaScript Set and Map The way , And a series of shorthand methods .

image.png

(6). configureWebpack

In addition to the above use chainWebpack To change webpack Outside of the internal configuration , We can also use configureWebpack To make changes , The difference between the two is chainWebpack It's chain modification , and configureWebpack More likely to replace and modify the whole . The sample code is as follows :

// vue.config.js
module.exports = {
    ...
    
    // config  The parameters are parsed  webpack  To configure 
    configureWebpack: config => {
        // config.plugins = []; //  This will directly  plugins  empty 
        
        //  Use  return  An object will pass through  webpack-merge  A merger ,plugins  Not empty 
        return {
            plugins: []
        }
    }
    
    ...
}
 Copy code 

configureWebpack Can be an object directly , It can also be a function , If it is an object, it will directly use webpack-merge Merge it , If it's a function , You can use it directly config Parameters to modify webpack Configuration in , Or return an object to do merge Handle .

You can run... In the project directory  vue inspect  To see your revised webpack Full configuration , Of course, you can also narrow down the scope of the review , such as :

#  Only view  plugins  The content of 
vue inspect plugins
 Copy code 

The above explains vue.config.js Some commonly used configuration item functions in , The specific configuration implementation needs to be combined with the actual project , The complete configuration items can be viewed :vue.config.js

3、 ... and , other

  1. filenameHashing : By default , Generated static resources contain in their filenames hash In order to better control the cache . However , It also requires index Of HTML Be being Vue CLI Automatically generated . If you can't use Vue CLI Generated index HTML, You can set this option to  false  To turn off the file name hash .

  2. pages: stay multi-page Build applications in mode . Every “page” There should be a corresponding JavaScript Entrance file . Its value should be an object , Object's key It's the name of the entrance ,value yes :

    One designated  entrytemplatefilenametitle  and  chunks  The object of ( except  entry  It's all optional );

    One specifies its  entry  String .

    module.exports = {
      pages: {
        index: {
          // page  Entrance 
          entry: 'src/index/main.js',
          //  Template source 
          template: 'public/index.html',
          //  stay  dist/index.html  Output 
          filename: 'index.html',
          //  When using  title  Option ,
          // template  Medium  title  The label needs to be  <title><%= htmlWebpackPlugin.options.title %></title>
          title: 'Index Page',
          //  The blocks included in this page , By default, it contains 
          //  The extracted universal  chunk  and  vendor chunk.
          chunks: ['chunk-vendors', 'chunk-common', 'index']
        },
        //  When using the entry only string format ,
        //  The template will be derived as  `public/subpage.html`
        //  And if it can't be found , Just go back to  `public/index.html`.
        //  The output filename is derived as  `subpage.html`.
        subpage: 'src/subpage/main.js'
      }
    }
     Copy code 
  3. css

     css: {
     modules: true,  
     sourceMap:true, //  Is it  CSS  Turn on  source map. Set to  `true`  Later it may affect the performance of the build .
     loaderOptions: {
       css: {
         localIdentName: '[name]-[hash]',
         camelCase: 'only'
       }
     }
    }
     Copy code 

    css.modules By default , Only  *.module.[ext]  The end of the file will be regarded as CSS Modules modular . Set to  true  After that, you can remove... From the file name  .module  And will all  *.(css|scss|sass|less|styl(us)?)  The document is regarded as CSS Modules modular .

    css.loaderOptions:

        towards  CSS  dependent  loader  Delivery options . for example :
    
       ```
       module.exports = {
         css: {
           loaderOptions: {
             css: {
               //  The options here are passed to  css-loader
             },
             postcss: {
               //  The options here are passed to  postcss-loader
             }
           }
         }
       }
       ```
     Copy code 

copyright notice
author[yuobey],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827001448395j.html

Random recommended