preface

This is my second study note on Webpack.

  • Webpack Study notes (1) : First meeting, please take care of

The previous blog introduced the basic concepts of WebPack and the approach to building a WebPack project from scratch. In this blog post, I want to talk about webPack’s basic property management, mainly two: resource management and output management. In this article, we continue the example from the first article.

Resource management

The ability to load and recognize javascript files and HTML files comes with WebPack out of the box. However, in an APP that runs in a browser, it is not enough to be able to use JavaScript and HTML. You also need to load other resources, such as images, CSS style files, and various types of data files. The solution webpack provides for loading these files is to install other loader tools in the project and reference the installed tools in the configuration file.

pretreatment

First, make a simple change to the previous project

  • dist/index.html
 <! DOCTYPEhtml>
 <html>
   <head>
     <meta charset="utf-8" />
  -  <title>start</title>
  +  <title>Management resources</title>
   </head>
   <body>
  -  <script src="main.js"></script>
  +  <script src="bundle.js"></script>
   </body>
 </html>
Copy the code
  • webpack.config.js
 const path = require('path');

 module.exports = {
   entry: './src/index.js'.output: {
 -   filename: 'main.js',
 +   filename: 'bundle.js'.path: path.resolve(__dirname, 'dist'),}}Copy the code

Load the CSS

  1. Install the necessary modules using the following command line: style-Loader and CSs-Loader

npm install –save-dev style-loader css-loader

  1. Configuration webpack. Config. Js
 const path = require('path');

 module.exports = {
   entry: './src/index.js'.output: {
     filename: 'bundle.js'.path: path.resolve(__dirname, 'dist'+)}module: {
 +   rules: [
 +     {
 +       test: /\.css$/i,
 +       use: ['style-loader'.'css-loader'], +}, +], +},};Copy the code
  1. Add it under the SRC folder. The CSS file

The directory structure after the change is as follows:

webpack-demo
| - package.json
| - webpack.config.js
| - /dist
    | - bundle.js
    | - index.html
| - /src
    | - style.css
    | - index.js
| - /node_modules
Copy the code
  1. Add and introduce styles
  • CSS
.hello {
    color: red;
  }
Copy the code
  • index.js
import _ from 'lodash'
import './style.css'

function component() {
    const element = document.createElement('div');
  
    // Lodash is imported in the current script using import
    element.innerHTML = _.join(['Hello'.'webpack'].' ');
    element.classList.add('hello');
  
    return element;
  }
  
  document.body.appendChild(component());
Copy the code
  1. Run the NPM command to package

npm run build

Once packaged, open the index.html file in your browser and see that the font is red

Load image

Change the webpack.config.js file:

const path = require('path');

 module.exports = {
   entry: './src/index.js'.output: {
     filename: 'bundle.js'.path: path.resolve(__dirname, 'dist'),},module: {
     rules: [{test: /\.css$/i,
         use: ['style-loader'.'css-loader'],}, {test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',},],},};Copy the code

Next, just reference the image you want

Load fonts

Change the webpack.config.js file:

const path = require('path');

 module.exports = {
   entry: './src/index.js'.output: {
     filename: 'bundle.js'.path: path.resolve(__dirname, 'dist'),},module: {
     rules: [{test: /\.css$/i,
         use: ['style-loader'.'css-loader'],}, {test: /\.(png|svg|jpg|jpeg|gif)$/i,
         type: 'asset/resource'}, {test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',},],},};Copy the code

Load the data

  1. Install the loader tool

npm install –save-dev csv-loader xml-loader

  1. Change the webpack.config.js file
 const path = require('path');

 module.exports = {
   entry: './src/index.js'.output: {
     filename: 'bundle.js'.path: path.resolve(__dirname, 'dist'),},module: {
     rules: [{test: /\.css$/i,
         use: ['style-loader'.'css-loader'],}, {test: /\.(png|svg|jpg|jpeg|gif)$/i,
         type: 'asset/resource'}, {test: /\.(woff|woff2|eot|ttf|otf)$/i,
         type: 'asset/resource'}, {test: /\.(csv|tsv)$/i,
        use: ['csv-loader'],}, {test: /\.xml$/i,
        use: ['xml-loader'],},],},};Copy the code

conclusion

For webPack resource management, there are only two steps:

  1. Install the appropriate*-loaderTools (if any)
  2. Configure this in webpack.config.js:
module: {
     rules: [{test: /\.css$/i.// Here matches the file type
         use: ['style-loader'.'css-loader'].// Declare the loader tool to be called},],},Copy the code

Output management

In many projects, it is not enough to generate just one file after packaging, and multiple JS files need to be generated simultaneously. This is where the webPack output needs to be managed. For output management, there are mainly four aspects:

  1. Output File Management
  2. The index. HTML file is automatically generated
  3. Clean up the /dist folder
  4. Generate the manifest file (the contents of this section will not be discussed for now)

Output File Management

  1. Adjust the project catalog
webpack-demo
| - package.json
| - webpack.config.js
| - /dist
| - /src
    | - index.js
    | - print.js
| - /node_modules
Copy the code
  1. Changing file Contents
  • src/print.js
export default function printMe() {
  console.log('I get called from print.js! ');
}
Copy the code
  • src/index.js
import _ from 'lodash';
import printMe from './print.js';

 function component() {
   const element = document.createElement('div');
  const btn = document.createElement('button');

   element.innerHTML = _.join(['Hello'.'webpack'].' ');

  btn.innerHTML = 'Click me and check the console! ';
  btn.onclick = printMe;

  element.appendChild(btn);

   return element;
 }

 document.body.appendChild(component());
Copy the code
  • dist/index.html
<! DOCTYPEhtml>
 <html>
   <head>
     <meta charset="utf-8" />
    <title>Management output</title>
    <script src="./print.bundle.js"></script>
   </head>
   <body>
    <script src="./index.bundle.js"></script>
   </body>
 </html>
Copy the code
  1. Configuration webpack. Config. Js
const path = require('path');

 module.exports = {
  entry: {
    index: './src/index.js'.print: './src/print.js',},output: {
    filename: '[name].bundle.js'.path: path.resolve(__dirname, 'dist'),}};Copy the code

The index. HTML file is automatically generated

  1. Installing a plug-in

npm install –save-dev html-webpack-plugin

  1. Configuration webpack. Config. Js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
   entry: {
     index: './src/index.js'.print: './src/print.js',},plugins: [
    new HtmlWebpackPlugin({
      title: 'Manage output',})],output: {
     filename: '[name].bundle.js'.path: path.resolve(__dirname, 'dist'),}};Copy the code

Clean up the /dist folder

Simply configure the output of webpack.config.js

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

 module.exports = {
   entry: {
     index: './src/index.js'.print: './src/print.js',},plugins: [
     new HtmlWebpackPlugin({
       title: 'Output Management',})],output: {
     filename: '[name].bundle.js'.path: path.resolve(__dirname, 'dist'),
     clean: true,}};Copy the code