Webpack

What is Webpack?

  • Official website www.webpackjs.com

In essence, Webpack is a static Module bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles.

The installation

Webpack is a modular code packaging tool implemented using Node.js. Therefore, we need to install WebPack first and set up the Node.js environment before installing it

 npm install -D webpack webpack-cli
Copy the code

Note: Global installation is not recommended, and some plug-ins are not compatible with older versions of WebPack. You can manually change the version in package.json and reinstall it

Webpack-cli: provides webpack commands and tools, such as create-react-app

Webpack: Webpack code, similar to React

use

Node_moudle /.bin/webpack // View the version./node_moudle/.bin/webpack -vCopy the code

Json file, you can add the following contents under script:

// package.json{... ."scripts": {
		"start": "webpack"	// scripts can be automatically searched in the./node_modules/.bin/ directory, so there is no need to complete the path}}Copy the code

Once written in package.json, you can start webpack directly from the terminal using NPM run start.

You can also use the NPX directive in the terminal: NPX webpack. This directive automatically looks for resources in the./node_moudle/.bin/ directory.

Webpack configuration

entry

The entry point indicates which module WebPack should use as a starting point for building its internal dependency diagram. Once at the entry point, WebPack finds out which modules and libraries are (directly and indirectly) dependent on the entry point.

Each dependency is then processed and finally exported to a file called Bundles, which we will discuss in detail in the next section.

You can specify an entry starting point (or multiple entry starting points) by configuring the Entry property in the Webpack configuration. The default value is./ SRC.

//webpack.config.js

module.exports = {
  entry: './path/to/my/entry/file.js'
};
// In this case, webpack will start packing with the file.js file as the entry point.
Copy the code

output

The Output attribute tells WebPack where to export the bundles it creates and how to name these files, with the default being./dist. Basically, the entire application structure is compiled into a folder in the output path you specify. You can configure these processes by specifying an output field in the configuration:

const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'}};// Create a folder named dist in the root directory and generate the packaged file my-first-webpack.bundle.js in that folder
Copy the code

loader

Loader is used to convert the module source code. Loader can preprocess modules before importing or loading them using import. As such, Loader is similar to “tasks” in other build tools and provides a powerful way to handle the front-end build steps. Loader can convert files from different languages (such as TypeScript) to JavaScript, or convert inline images to data urls. Loader even allows you to import CSS files directly into JavaScript modules.

Loader has the following features:

  • Support chain operation
  • Support synchronous and asynchronous
  • The query parameters can be received to pass the configuration to the Loader
  • You can useoptionsObject to configure the Loader

For example, webpack can actually load various files such as CSS, TXT files, but the default is js file type import. Loader can tell Webpack to import CSS files correctly, or convert JS files to TS files. Loader components must be installed:

npm install --save-dev css-loader
npm install --save-dev ts-loader
Copy the code

After installation, configure loader rules in webpack.config.js.

//webpack.config.js  

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

The instance

Through the configuration of Entry, output and loader, the basic functions of WebPack can be realized.

/ / resources organization structure as follows - / dist / / project after packaging storage directory, / node_modules / / third-party modules - / SRC / / working directory, CSS/images/js / -- index. Js -  /template ---- index.html -- webpack.config.js -- package.jsonCopy the code

Entry file index.js File contents

import fn1 from './js/fn1.js'
import fn2 from './js/fn2.js'
import img from './images/logo.png'
let bottunElement = docunment.qs('#btn1')

console.log('fn1',fn1);

let image = new Image();
image.src = img;
document.body.appendChild(image);

bottunElement.onclick = function(){
    fn2();
}
Copy the code

Fn1. js file contents

export default 100 ;
Copy the code

Fn2. js file contents

console.log('resolved');
Copy the code

The contents of the index. HTML template file:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title><document></title>
</head>
<body>
    <h1>webpack</h1>
    <button id="btn1">
        click
    </button>
</body>
</html>
Copy the code

Webpack.config.js configuration content

const path = require('path');

module.exports = {
    entry: {
        'index': './src/index.js'
    },

    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/[name].js'
    },
    
    module: {
        rules: [{test: /\.(png|jpe? g|gif)$/,
                use: {
                    loader: "url-loader".options: {
                        // placeholder [name] The name of the source resource module
                        // [ext] the suffix of the source resource module
                        name: "[name]_[hash].[ext]".// The packing location
                        outputPath: "./images".// The url of the packaged file
                        publicPath: '.. /dist/images'.< 100 bytes, convert to base64 format
                        limit: 100}}}, {test: /\.css$/,
                use: [
                    // "style-loader",
                    {
                        loader: MiniCssExtractPlugin.loader
                    },
                    {
                        loader: "css-loader".options: {
                            // Enable/disable URL () processing
                            url: true.// Enable/disable @import processing
                            import: true.// Enable/disable Sourcemap
                            sourceMap: false}}]}}Copy the code