This article is written by the chief writer of the public number Byte backjourney, Who has been certified as a tuquai community columnist. The following articles will bring you a series of Webpack articles, please look forward to ✌️. Welcome to join the Tuque community, create a wonderful free practical technology tutorial, speed up the spread of technology!

If you think we wrote well, remember to like + follow + comment three times, encourage us to write a better tutorial 💪

Why build tools? If you only know JS + CSS + HTML, plus jquery at most, are you confused when you hear build tools? Instead of learning WebPack, I recommend learning the Vue or React frameworks, both of which have their own scaffolding. Scaffolding is when someone builds your original project with a build tool, so you can do front-end development without knowing the build tool. But that’s basically what a basic front-end is all about, giving me an environment to write business code in peace.

In fact, there is nothing wrong with just doing the above work. You can delve into CSS, explore JS deep syntax, and even refine algorithms and data structures.

I want to say that if you ever get interested in Webpack, ok, welcome to the big front end world! Webpack is a powerful and extensible front-end build tool, and other similar tools including Grunt, gulp and others are implemented based on Node.js for the underlying driver platform.

Why build or compile? Front-end build packaging is important because things like ES6, LESS, and SASS, template syntax, vUE directives, and JSX cannot be executed directly in the browser and must go through the build process for the project to run. In addition to these, front-end builds can address web application performance issues such as dependency packaging, resource embedding, file compression, and hash fingerprinting. I will not expand the specific, in short, front-end construction engineering has been the trend.

As for why I choose WebPack, because the tool configuration is very flexible, supports plug-in extension, the community is very rich, and the official iteration update speed is fast. As a programmer, it is a reliable choice.

So, without further ado, let’s get straight to the business and teach you half an hour to build a small project using WebPack. Learn things quickly, you can not understand every concept, do first, otherwise you will be a week to learn.

1. Node installation

First of all, ensure that your computer has the Node environment, Node installation is relatively easy, directly download the node installation package from the official website https://nodejs.org/en/. Note that there are two versions here, the left is the stable version, the right is the latest version, generally use the stable version. The specific installation process is not the focus of this article, there are many installation tutorials available online. With the Node environment, you can later install Webpack via NPM, a package management tool that automatically installs NPM when you install Node. If necessary I can also write a tutorial in my official account.

Webpack installation and configuration

1. Webpack installation

First create a my_webpack folder as the project folder, go to the current folder, use the command line tool CMD to execute the following command:

npm init -y
npm install webpack webpack-cli --save-dev
Copy the code

After the installation, check the version and confirm that the installation is successful

 ./node_modules/.bin/webpack -v
Copy the code

After a successful installation, this content will appear under the folder

2. Webpack configuration

Then create an empty configuration file in the root directory, webpack.config.js, and create the following:

'use strict'
const path = require('path');
module.exports = {
    entry: {
        index: './src/index.js',},output: {
        path: path.join(__dirname,'dist'),
        filename: 'index.js'
    },
    mode: 'production',}Copy the code

Entry indicates the package entry, output indicates the output address and file name to be packaged, and mode indicates the development environment. Js and helloWebpack. js in the SRC folder. Finally, create an index. HTML file in the dist folder.

Enter the following content in the helloWebpack. js file:

export function hellowebpack() {
    return 'hellowebpack'
}
Copy the code

Then reference the function in the helloWebpack.js file in index.js

import {hellowebpack} from './hellowebpack'
document.write(hellowebpack())
Copy the code

/node_modules/.bin/, we’ll see an extra index.js file in dist, and we’ll see the zip code.

We create the following content in the file indext.html in the dist directory, and you can see it when you open the page in your browser.


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="./index.js" type="text/javascript"></script>
</body>
</html>
Copy the code

In the SRC directory is the development content, followed by webpack code packaging, in the dist directory will generate an index.js file, and finally referenced in the index.html page, this is the basic flow of webpack packaging project.

/node\_modules/. Bin /. Json file by adding a configuration “build”: “webpack” to the script node of the package.json file, then deleting the dist directory and running NPM run build.

3. Webpack starting sample

Webpack parses ES6

At this stage, we need to master a new concept: loaders. The so-called loaders means to load and parse files or file contents that webPack does not support originally, so as to realize the purpose of application. Es6 parsing is supported by JS, but es6 parsing is not supported by BABel-loader, which relies on Babel. Install babel-loader

npm i @babel/core @babel/preset-env babel-loader -D
Copy the code

Create the.babelrc file in the root directory and add the following

{
    "presets": [
        "@babel/preset-env"]},Copy the code

Then add the Module property to the webpack.config.js file, which is a rules collection with the following contents

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

Each element of the Rules collection is the configuration information of a file type. Here there is only one JS file. CSS, LESS and images of various formats will be discussed later. Test is a re that matches the file suffix; Use Indicates the loader name.

The helloWebapck. js file created in the previous example is referenced in the index.js file. The import is es6, some browsers do not support ES6, if you use webpack directly on this browser will be wrong, but just installed and configured babel-loader, can implement es6 method parsing, Babel can also parse JSX syntax. Now run the NPM run build to build and you can see that the result is successful. (In fact, you can verify the effect of es6 parsing with an IE browser.)

2. Webpack loads CSS, less and other style files

Css-loader is used to load CSS files and generate CommonJS objects, and style-loader is used to insert styles into the head via the style tag

Install the loader

npm i style-loader css-loader -D
Copy the code
// ...
module: {
        rules: [{test: /.js$/.use: 'babel-loader'
            },
            {
                test: /.css$/.use: [
                    'style-loader'.'css-loader']},]}// ...
Copy the code

Note that there are two loaders used to parse CSS, so the use object is an array. We need to pay special attention to the loader sequence, which is to write style-loader first, and then csS-loader, but to load CSS-loader first. After parsing the CSS, pass the CSS to style-loader.

Add a public. CSS file to your project and write a style inside:

.color-text {
    font-size: 20px;
    color: red
}
Copy the code

Reference this file in the SRC /index.js file, as shown below.

We know that this file is used as the entry file for packaging. After packaging, we can directly add a div tag to the index. HTML file in the dist directory and add the style name color-text to verify the effect of style packaging and reference

<body>
    <script src="./index.js" type="text/javascript"></script>
    <div class="color-text">text-color</div>
</body>
Copy the code

Then run the NPM run build command. After successful execution, open the index.html file in the dist directory in the browser and you will see the following:

CSS files cannot be parsed. In this case, you need to install less dependencies and add configurations.

Install dependencies related to less

npm i less less-loader -D
Copy the code

Add less file parsing configuration

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

After these steps are complete, run the NPM run build command to pack, and finally view dist\index.html in your browser. You’ll see the same effect.

3. Webpack loads images

Image packaging in Webpack is similar to the above steps, but the loader is different.

The installation file – loader

Run the following command to install the file-loader dependency

npm i file-loader -D
Copy the code

Then add the parse configuration under the module node of the webpack.config.js configuration file:

{
    test: /.(jpg|png|gif|jpeg)$/.use: 'file-loader'
}
Copy the code

Place an image in the SRC directory, add the background image style to the public. CSS file in the same directory, and type in the following:

.color-text {
    font-size: 20px;
    color: red;
    height: 500px;
    background: url(beautiful.jpg) no-repeat;
}
Copy the code

Then run the NPM run build command to build, and there was no picture displayed when we finally executed, but we found the packaged picture just now in the dist directory, as shown in the figure. This is embarrassing, even though the image is packaged, the problem is THAT I still copy and copy the name and quote it every time, which is not scientific.

Is there a better way to load images? The answer is yes! See the steps:

Install the url – loader

npm i url-loader -D
Copy the code

Url-loader is directly embedded with file-loader, which is reencapsulated. You can delete the file in the configuration file and replace it with the URL.

Add configuration content to the webpack.config.js file. Note that limit is the upper limit of the image size in bytes. If the image size is smaller than this value, it will be packaged as Base64, otherwise it will remain an image. Since this image has 120K, I’m going to set it to 160,000, which is almost 150k plus.

{
    test: /.(jpg|png|gif|jpeg)$/.use: [{
        loader:'url-loader'.options: {
            limit:160000.name: 'imgs/[name].[hash].[ext]'}}}]Copy the code

Execute NPM run build to check the effect and find it successful. Then look at the index.js file in dist directory and find that there is much more content, in fact, there is more base64 data of this image.

Well, that’s all for this article. If you follow my steps, you can easily get started. Of course, there is still a lot to learn about WebPack before it really reaches the application level, such as how to load VUE directives or JSX syntax, how to package components, etc. I will continue with the introductory tutorial later.

Want to learn more exciting practical skills tutorial? Come and visit the Tooquine community.

If you think we did a good job, please like ❤️ ❤️