webpack.config.js

In the process of using webPack, we may have some configuration conflicts with the default configuration of WebPack or want to extend the configuration items of WebPack

On the one hand, we can configure it in the form of parameters. For details, please refer to the official website

#All of the cli parameters reference https://webpack.js.org/api/cli/
$ npx webpack --entry ./main.js --output-path build
Copy the code

But there are some complications with this configuration

  1. If there are too many configuration items, the code becomes too long to read and maintain

  2. If the command is not configured in package.json, the corresponding command is executed manually

    If the command is executed in an incorrect path, a compilation error occurs

So in most cases, our configuration will be configured in the corresponding webPack configuration file, which can be loaded directly at compile time

The default webpack configuration file is located in the project root directory. The default configuration file is called webpack.config.js

webpack.config.js

const path = require('path')

// It runs in node by default and needs to export configuration objects in CJS mode
// If the option is configured in the configuration file, use the configured value; if not, use the default value
module.exports = {
  // entry -- relative path
  entry: './src/main.js'.// Exit is an object
  output: {
    // Output folder configuration, must be an absolute path
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js'}}Copy the code

Manually specify the configuration file

In some cases, you don’t want to use the default configuration file, or you need to use a different configuration file depending on your runtime environment

"scripts": {
    "build": "webpack --config w.config.js" // Use --config or -c to specify a custom configuration file
  }
Copy the code

Webpack uses the configuration file to pack if there is a specified configuration file or a default configuration file,

If the corresponding configuration file cannot be found, the system uses the default configuration

Dependency diagram

When WebPack processes an application, it finds the entry file based on the command or configuration file

From the entry point, a dependency diagram is generated that contains all the modules needed in the application (such as.js files, CSS files, images, fonts, and so on)

It then traverses the structure of the diagram, packaging the modules.

This means that if a module is not introduced for use, it will not be weighted into the WebPack dependency diagram and will not participate in the packaging process

Similarly, even if a module is introduced, if there are unused methods in it, WebPack uses Tree shaking technology to remove unused methods during packaging to keep the size of the packaged package to a minimum

loader

By default, WebPack can only import JS modules. For other types of modules, WebPack does not know how to compile and package them.

A translator is needed to tell WebPack how to compile these modules

use

  1. Inline schema
  2. Configuration Mode (Common)

Inline schema

// Write the loader to be used before the imported module
// Loaders are used between loaders and imported resources! segmentation

// Import resources from right to left, and use the corresponding Loader to parse the resources after removing them
import 'style-loader! css-loader! ./css/index.css'
Copy the code

Configuration mode

module.exports = {
  module: { // The top-level configuration option has a module that represents the configuration when parsing the module
    rules: [ // Module parsing Rule type is Rule[]
      { / / object Rule
        test: /\.css$/.// re matches which files fit this rule
        use: [ // Need to use the module list UseEntry[]
          // Loader is loaded from bottom to top, from right to left, and from back to front
          { 
            loader: 'css-loader'.// The module to use
            options: {} // Configuration parameters passed to the module can be passed without parameters}]}}Copy the code
module: {
  rules: [{test: /\.css$/,
      use: [
        {
          loader: 'css-loader'}]}]}// ====> Loader if no configuration parameters need to be passed, the format can be shortened to a string

module: {
    rules: [{test: /\.css$/,
        use: [
          'css-loader'}]}}Copy the code
module: {
    rules: [{test: /\.css$/,
        use: [
          'css-loader'}]}}// ====> If there is only one loader in use, you can continue the shorthand

// Short form 1
module: {
  rules: [{test: /\.css$/,
      use: 'css-loader'}}]// Short form 2
module: {
  rules: [{test: /\.css$/,
      loader: 'css-loader'}}]Copy the code

CSS packaging

css-loader

#Css-loader allows WebPack to identify and compile CSS modules
$ npm install css-loader -D
Copy the code

Configuration -- Loading loader

module: {
  rules: [{test: /\.css$/,
      use: 'css-loader'}}]Copy the code

Webpack parses the CSS module normally, but does not apply the styles to the elements

Therefore, another loader is needed to assist the style-loader operation

Style-loader inserts the code parsed by CSS-Loader into the head in inline style (in-page style)

$ npm i style-loader -D
Copy the code

configuration

module: {
  rules: [{test: /\.css$/,
      use: [ // Note that the loading order is from bottom up, right to left, and back to front
        'style-loader'.'css-loader']]}}Copy the code

CSS preprocessor packaging

The following uses less as an example

#Less-loader relies on lessc provided by less to compile.
#Lessc is called to help compile the less-loader

#Less loader can be installed only in the project
#Less will be downloaded and used as a dependency of less-loader
$ npm i less less-loader -D
Copy the code
// Configuration section
{
  test: /\.less$/,

    use: [
      'style-loader'.'css-loader'.'less-loader']}Copy the code

Browser compatibility

In development, we need to deal with compatibility issues and adapt different features supported by different browsers, such as CSS features and JS syntax

We then need a tool that queries browser adaptation separately and shares the adaptation information between tools

The tool is Browserslist, and it uses its dependent package caniuse-Lite to look up browser compatibility on the Caniuse website, and then shares browser compatibility data between all the tools that need to do browser compatibility adaptation

#If a tool needs to use Borwserslist, it will automatically have Browserslist as its dependency and automatically install Browserslist
#So in most cases, we don't need to install Borwserslist actively
$ npm i browserslist -D
Copy the code

Command line

#If there is no query condition, check whether there is a configuration file. If there is, use the configuration file. If there is no query condition, use the built-in default configuration
$ npx browserslist

#When querying, use the query criteria to query
#Multiple conditions are separated by commas
$ npx browserslist ">1%, last 2 version, not dead"
Copy the code

Custom Configuration

Configuration mode 1 -- package.json

The use of commas to indicate a union, that is, an or relationship

"browserslist": [
  "1%" >."last 2 versions"."not dead"
]
Copy the code
"browserslist": {
  "development": [
    "1%" >."last 2 versions"."not dead"]."production": [
    "0.5%" >."not dead"]}Copy the code

Configuration Method 2: Create a. Browserslistrc file in the project root directory

A newline is used to indicate a union, that is, an or relationship

> 2%
last 2 versions
not dead
Copy the code

Browserslist configuration rules

The following are common configuration rules. You can click the link to view more configuration rules

The rules instructions
defaults Default browser for Browserslist (> 0.5%, last 2 Versions, Firefox ESR, Not Dead)

Firefox ESR — Extended Support for Firefox
5% 5% market share, can be used with >=, < and <=, etc
dead No officially supported or updated browser for 24 months
last 2 versions Last 2 versions of each browser
not ie <= 8 Exclude the browser selected by the previous query
Relational operator instructions
Or or comma or newline Union, the relation of or
and Intersection refers to the relationship of union
not Take the inverse to indicate the non-set relation

stats

By default, WebPack outputs a lot of information during compilation, but in some cases, if you only want to focus on a certain part of the information, you can set the stats option so that WebPack outputs only the information you need during compilation

module.exports = {
  / /...
  stats: 'errors-warnings'};Copy the code

Load the Vue file

In React, components are written using JSX, so the component name suffix in React is js or JSX.

So we can use babel-loader to load the React component

But in Vue files, writing components uses more of a template syntax (although you can also write Vue components using JSX),

Vue components generally use single-file components with a. Vue suffix

Therefore, we need to use a specific loader to process the VUE components while they are being built

 #The installation
 #Vue-laoder is used to parse VUE files
 #Vue-template-compiler parses templates in vUE components before vue-Loader parses VUE files
 #Vue-template-compiler should be installed manually in earlier vue-loader
 #The latest VUE-loader is no longer required
  npm install vue-loader -D
Copy the code

Webpack. Config. Js - configuration

// This plug-in is integrated with vue-loader
const { VueLoaderPlugin } = require('vue-loader')

module: {
  rules: [{// The style part of the vue component is automatically separated into separate parts that are parsed by the loader that processes the style
      // Therefore, there must be a loader with the corresponding parsing style and corresponding configuration
      test: /.scss$/,
      use: [
        'style-loader'.'css-loader'.'postcss-loader'.'sass-loader']},// Parse vue's single-file components
   {
     test: /.vue$/,
     use: [
       'vue-loader']]}},plugins: [
  // Use vue-loader to load THE SFC file of vue
  // The VueLoaderPlugin can be used to parse vue SFC files
  new VueLoaderPlugin(),
]
Copy the code