1. Introduction

Review: Introduction to WebPack briefly introduces the five concepts of Webpack and writes two examples together. We know that WebPack itself can only handle JS and JSON files, other types of files need to cooperate with Loader or plugin; We also know that the Loader and plugin need to be downloaded using NPM Install (there are other ways to download, of course). If you don’t remember, you can go back and review it

This article will start with the file and talk about how to package it, depending on the type of file, and which Loader or plugin you need to use.

For the sake of space, only the necessary code will be listed, the complete code is here

2. Package resources

2.1. Package style resources

We usually use CSS, less, and Sass to write styles. Different loaders are used to package different types of style resources.

Use the loader

  • The CSS file: style-loader, css-loader;
    • css-loader: Converts CSS files into commonJS modules and loads them into JS. CSS code is converted into style strings. The resulting CommonJS module can be interpreted as code that dynamically styles elements using JS.
    • style-loader: createStyle tagsThat will becss-loaderThe generated style resource is inserted and added to the head to validate the style.
  • . Less file: style-loader, css-loader, less-loader;
    • less-loader: compiles less files into CSS files.
    • Note: if you want toless-loaderTo work, you still need to downloadless (npm install less -D).
  • , SCSS/sass files: style-loader, css-loader, sass-loader;
    • sass-loader: compile sass or SCSS files into CSS files;
    • Note: if you want tosass-loaderTo work, you still need to downloadnode-sass (npm install node-sass -D).

Webpack configuration

When configuring the Loader, write rules separately for different files.

// webpack.config.js

const { resolve } = require('path');
module.exports = {
  entry: './src/index.js'.output: {
    filename: 'built.js'.path: resolve(__dirname, 'dist')},module: {
    rules: [{test: /\.css$/,
        use: [
          'style-loader'.'css-loader'] {},test: /\.less$/,
        use: [
          'style-loader'.'css-loader'.'less-loader'] {},test: /\.s[ac]ss$/,
        use: [
          'style-loader'.'css-loader'.'sass-loader',]}]},plugins: [].mode: 'development'
}
Copy the code

2.2. Package HTML resources

To package HTML resources, use a plugin: html-webpack-plugin.

Use the plugin

HTML – webpack – the plugin:

  • If no argument is passed:
    • New HTMLWebpackPlugin() : Creates an empty HTML file in the output folder of the configuration, automatically importing all the resources that are packaged for output, including JS, CSS… ;
    • Set the template parameter to copy the set ‘./ SRC /index.html’ file to the configured output folder and automatically import all the resources packaged for output.

Webpack configuration

const { resolve } = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js'.output: {
    filename: 'built.js'.path: resolve(__dirname, 'build'),},module: {
    rules: []},plugins: [
    /** * html-webpack-plugin * 1) -- new HTMLWebpackPlugin() : creates an empty HTML file in the configured output folder, and automatically introduces all the resources that are packaged for output, including JS, CSS... * 2) The template parameter: copies the set './ SRC /index.html' file to the configured output folder and automatically imports all the resources packaged for output */
    new HTMLWebpackPlugin({
      template: './src/index.html'}),].mode: 'development'
Copy the code

2.3. Package image resources

Use the loader

  • url-loader: is used to handle image resources in CSS, butCannot handle img tags in HTML:
    • url-loaderBased on thefile-loaderRun, so downloadUrl - loader and file - loader;
    • Can be achieved byoptionsAdd configuration items to Loader (used in this example only) :
      • Limit: The size limit of the image. If the size exceeds the limit, it will be processed as base64.
      • EsModule: URl-loader uses ES6 by default. Set to false: turns off its ES6 modularity and uses CommonJS parsing;
      • Name: Rename the image. [hash:10] – Takes the top 10 bits of the hash of the image; [ext] – Take the extension of the original file.
  • html-loaderImg image of HTML file (responsible for importing IMG so it can be processed by URl-Loader) :
    • You can also go throughoptionsAdd configuration items to Loader:
      • EsModule: set to false: turns off its ES6 modularity and uses CommonJS parsing;

Webpack configuration

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js'.output: {
    filename: 'built.js'.path: resolve(__dirname, 'build')},module: {
    rules: [{test: /\.less$/,
        use: [
          'style-loader'.'css-loader'.'less-loader'] {},/** * url-loader: * 2) Url-Loader runs on file-loader, so you need to download url-loader and file-loader * 3) Options: * limit: If the image size is less than 8Kb, it will be processed as base64; * esModule: URl-loader uses ES6 parsing by default. Set to false: turns off its ES6 modularity and uses CommonJS parsing; * name: Rename the image. [hash:10] - Takes the top 10 bits of the hash of the image; [ext] - Take the extension of the original file. * /
        test: /\.(jpg|png|gif|jpeg)$/,
        loader: 'url-loader'.options: {
          limit: 8 * 1024.esModule: false.name: '[hash:10].[ext]'}}, {/** * html-loader: processes the IMG image of the HTML file (responsible for importing img, which can be processed by url-Loader) */
        test: /\.html$/,
        loader: 'html-loader'.options: {
          esModule: false}}},plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'})].mode: 'development'
}
Copy the code

2.4. Package other resources

For example, the font icon file ~ is often used in projects

Loader to use:file-loader

Webpack configuration


const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/indes.js'.output: {
    filename: 'built.js'.path: resolve(__dirname, 'build')},module: {
    rules: [{test: /\.css$/.//
        // use: ['style-loader', 'css-loader']
        //
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader'}]}, {// exclude: Matches all files except the exclude value
        exclude: /\.(css|js|html|png|gif|jpg)$/,
        loader: 'file-loader'.options: {
          name: '[hash:10].[ext]'}}},plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'})].mode: 'development'
}
Copy the code

3. Configure the development environment – devServer

3.1. Brief introduction to devServer

DevServer: Development server for automation (automatic compilation, automatic browser opening, automatic browser refreshing)

Features: It is only compiled and packaged in memory, with no output (no new folder in the project)

How to start:

  • npx webpack serve(webpack-cli: 4.x);
  • npx webpack-dev-server(webpack-cli 3.x);

3.2. Webpack configuration

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/indes.js'.output: {
    filename: 'built.js'.path: resolve(__dirname, 'build')},module: {
    rules: []},plugins: [].mode: 'development'.devServer: {
    contentBase: resolve(__dirname, 'build'), // The path of the project after construction
    compress: true.// Whether to use gzip compression
    port: 3000.// Set the port number
    open: true // Whether to open the browser automatically}}Copy the code

4. Think and summarize

4.1. Package different types of files

  • The CSS file:style-loader.css-loader;
  • . Less file:style-loader.css-loader.less-node; (Installation requiredless)
  • SCSS/sass files:style-loader.css-loader.sass-loader; (Installation requirednode-sass)
  • .html file:html-webpack-plugin;
  • Image files (.png/.jpg/.jepg/.gif, etc.) :url-loader.html-loader;
  • Other documents:file-loader.

4.2. Configure different ways to write Loader

Notice that loader is written differently in this article. In general, if a loader has options configured, it is written separately.

module.exports = {
  entry: './src/indes.js'.output: {
    filename: 'built.js'.path: resolve(__dirname, 'build')},module: {
    rules: [{test: /\.css$/.//
        // use: ['style-loader', 'css-loader']
        //
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader'}]}, {exclude: /\.(css|js|html|png|gif|jpg)$/.//
        loader: 'file-loader'.options: {
          name: '[hash:10].[ext]'}}},plugins: [].mode: 'development'
}
Copy the code

Think 4.3.

Why don’t you try to string these configurations together and write a demo? After that, we can correct the answer. I put my homework here