Learning one of webacks: from the simplest webacks

Time:2019-12-2

Read a lot of webback tutorials, mostly about a bunch of configuration, a bunch of plug-in use. This kind of article looks like an official document, or Xinhua dictionary. I want to go back to the original idea and introduce webback step by step based on practical use.

Starting from the simplest example, this example is only to describe the simplest webback function and realize the simplest requirement: to display a paragraph of text on the browser.

Traditional way

First of all, we have aindex.html, this HTML only introducesindex.jsa.jsandb.js

<!Doctype html>
<html>
  <head>
      <meta name="charset" content="utf-8">
      <title>webpack</title>
  </head>
  <body>
    <script type="text/javascript"></script>
    <script type="text/javascript"></script>
    <script type="text/javascript"></script>
  </body>
</html>

staya.jsVariable declared invar a = 1;Inb.jsVariable declared invar b = 2;。 Because the scope is shared in this way, a and B are both mounted on the window, so inindex.jsThe values of a and B can be accessed directly in.

stayindex.jsIn, we create a DOM and mount it on HTML:

var dom = document.createElement('p');
dom.innerHTML = `a=${a}; b=${b}`;
document.body.appendChild(dom);

Finally, it will be displayed on the browsera=1; b=2

Although it is simple to use, there are potential problems:

  1. When the browser loads, it will first load the HTML file, and then load each JS file in turn according to the script tag in the HTML. In this way, for each JS file, the browser will send a request to the server. If a large number of files are introduced, the number of requests sent will be too many, which will cause certain pressure on the server. Moreover, a single file may not be large, which is not cost-effective compared with the cost of the browser to establish links and disconnect links for each request. To solve this problem, you need to package multiple JS files into a single package.
  2. The loading order of JS files cannot be strictly guaranteed, such asindex.jsIt’s loaded, but it depends ona.jsNot loaded yet. Of course, this question can be usedrequire.jsSolve.
  3. JS code introduced by different script tags will pollute the global scope, such asa.jsA declared in is directly mounted on the window. If a variable is declared in other files, there will be conflicts. This problem can be solved by executing the function immediately.

Although there is a way to solve it, I always feel that it is not so perfect. It can cure the symptoms rather than the root cause. Back to the running environment of JS, this is because JS code needs to run in the browser. If running in a node environment, you can directly use the commonjs specification. Each file is a module, and the scope of each module is independent. You can solve the problem of module dependency and loading through require. Even the module mechanism of ES6 can be used in node, which can also solve this problem. Obviously, this way of writing code is much simpler, but only in the node environment. And an important role of webback is to make the code you write in this way run in the browser.

Webback mode

a.jsandb.jsAs two modules, export variables A and B through the export of ES6, and import them in index.js:

//a.js
export var a = 1;

//b.js
export var b = 2;

//index.js
import {a} from './a.js';
import {b} from './b.js';
var dom = document.createElement('p');
dom.innerHTML = `a=${a}; b=${b}`;
document.body.appendChild(dom);

Finally, we want to use webpack to package it into a separate file and mount it directly toindex.htmlMedium. From scratch, install webpack.

  1. Create a new folder in this foldernpm init, initialization.
  2. installwebpackandwebpack-cliRunnpm install webpack webpack-cli -Dwebpack-cliCommand line tools are provided for webback, so that we can use webback directly in the command line
  3. Set up the SRC folder, anda.js,b.jsandindex.jsStore in SRC folder. This folder holds the original documents
  4. Create dist folder to store compiled files, i.e. single packed files
  5. takeindex.htmlPut it in the SRC folder, and the reference is notindex.js, but the packed one is located in the dist directorybundle.jsfile

    <script type="text/javascript"></script>
  6. Configure webpack. The configuration of webpack is to create a new one directly under the root directorywebpack.config.js, configured as follows:

    const path = require('path');
    
    module.exports = {
      entry: './src/index.js',
      output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js'
      }
    }
    • Entry is a packaged entry file, that is, it tells webpack which file to package. What is specified here isindex.js。 Due toindex.jsinimporta.jsandb.js, so when the web pack is packaged, it willa.jsandb.jsIntroduce. From here, we can see that we can only tell the webback entry file, and all the dependent files webback will find and solve by itself.
    • Output is to tell webpack where to put the packed files. Path specifies the path of the packed file, and filename specifies the name of the packed file. All in all, the packed file is in the dist directorybundle.js
  7. staypackage.jsonMake a configuration under script in:

    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack" 
      },
  8. Direct operationnpm run buildThe node will automatically execute the webpack. At this time, you can see the generated JS file (only one) in the dist directory. Theindex.htmlPut it in the browser and you’ll see the final effect.

More than that

From the above example, we can see that after using webback, we have solved various problems encountered in the traditional way. Of course, webback can do more than that. For example, when writing code, there may also be these requirements:

  • Code conversion: compile typescript into JavaScript, SCSS into CSS, etc.
  • File Optimization: compress JavaScript, CSS, HTML code, compress and merge pictures, etc.
  • Code segmentation: extract the common code of multiple pages, and extract the first screen without executing part of the code to record it asynchronously.
  • Module merging: there will be many modules and files in the project adopting modularization, and module classification needs to be merged into one file through building function.
  • Auto refresh: listen for local source code changes, and automatically rebuild and refresh the browser.
  • Code verification: before the code is submitted to the warehouse, it needs to verify whether the code conforms to the specification and whether the unit test passes.
  • Automatic release: after the code is updated, the release code on the outgoing line is automatically built and transmitted to the release system.

We need a tool to help us solve these problems and complete the whole processstructureTechnological process. The purpose of using the build tool is to make it more convenient for us to write code. We can use the updated features without paying too much attention to browser compatibility. We can save a lot of mechanical repetitive work, such as the browser will automatically refresh after modifying the code, so as to improve our development efficiency.

Of course, there are many excellent building tools before web pack, such as grunt, gulp, etc. It’s not too much to call webback the most popular build tool. Webback is powerful not only in itself, but also in many plug-ins based on webback, providing a powerful ecosystem. There are many things webpack can do, and we will continue to learn step by step.

Recommended Today

Some brief introductions using Kafka: 1 clustering 2 Principle 3 terminology

[TOC] Section I Kafka cluster Before inheriting If you are a developer and are not interested in building Kafka cluster, you can skip this chapter and look at tomorrow’s content directly If you think it’s no harm to know more, please keep reading As a reminder, there are many figures in this chapter Kafka cluster […]