Read a lot of Webpack tutorials, most of them are on a bunch of configuration, a bunch of plug-in use. These articles look a bit like official documents, or Xinhua dictionaries. I want to go back to my roots and take a step by step introduction to WebPack based on actual use.
Start with a simple example, intended only to describe the simplest webpack functionality, that fulfills one of the simplest requirements: to display a piece of text on the browser.
The traditional way
First we have an index.html, which only introduces index.js, A.js and b.js.
<html>
<head>
<meta name="charset" content="utf-8">
<title>webpack</title>
</head>
<body>
<script type="text/javascript" src="./a.js"></script>
<script type="text/javascript" src="./b.js"></script>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
Copy the code
Var a = 1; var a = 1; , var b = 2 is declared in b.js; . Since the scope is shared in this way, both a and B are mounted on the window, so the values of a and B can be accessed directly in index.js.
In index.js, we create a DOM and mount it to the HTML:
var dom = document.createElement('p');
dom.innerHTML = `a=${a}; b=${b}`;
document.body.appendChild(dom);
Copy the code
Finally, the browser will display a=1; B = 2.
This is simple, but potentially problematic:
- When loading, the browser will load the HTML file first, and then load each JS file in turn according to the script tag in the HTML. So for each JS file, the browser sends a request to the server. If the number of files brought in is large, the number of requests sent will be excessive, putting a certain strain on the server. Also, individual files may not be large enough to justify the cost to the browser of establishing and breaking links on every request. To solve this problem, you need to package multiple JS files into a single package.
- Loading order of JS files is not strictly guaranteed, for example
index.js
Load finished, but it depends ona.js
It’s not loaded yet. Of course, this question can be usedrequire.js
To solve. - Js code introduced by different script tags can pollute the global scope, for example
a.js
If you declare a variable in a file, it will cause a conflict. This problem can be solved by executing the function immediately.
Although there is a solution, but the total feeling is not so perfect, treating the symptoms rather than the root cause. Back to the js runtime environment, this is all because the JS code needs to run in the browser. If you are running in a Node environment, you can use the CommonJS specification directly. Each file is a module, and each module is scoped independently. Require can solve module dependencies and load problems. You can even take advantage of the ES6 module mechanism in Node to solve the same problem. Obviously, this is a much simpler way to write code, but only in a Node environment. One of the key features of WebPack is that it allows your code to run in the browser.
Webpack way
A. js and B. js, as two modules respectively, export variables A and B through ES6 export, and import them through import 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);
Copy the code
Finally, we want to use Webpack to package it into a single file and mount it directly into index.html. From scratch, install webPack.
-
Create a new folder, and in that folder NPM init, initialize.
-
To install webpack and webpack-cli, run NPM install webpack webpack-cli -d. Webpack – CLI provides command line tools for Webpack, allowing you to use Webpack directly from the command line
-
Create a SRC folder and store a.js, B.js and index.js in the SRC folder. This folder holds the original files
-
Create a dist folder to store compiled files, which are packaged individual files
-
Put index.html in the SRC folder, and instead of referring to index.js, you’ll refer to the bundled bundle.js file in the dist directory
<script type="text/javascript" src=".. /dist/bundle.js"></script> Copy the code
-
Configuration webpack. To configure webpack, create a new webpack.config.js file in the root directory as follows:
const path = require('path'); module.exports = { entry: './src/index.js'.output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js'}}Copy the code
- Entry is a packaged entry file that tells WebPack which file to pack
index.js
. Due to theindex.js
In theimport
thea.js
andb.js
, so WebPack will be packed at the same timea.js
andb.js
Introduction. As you can see from this, you just tell WebPack the entry file, and WebPack will find and resolve all the dependency files itself. - Output tells WebPack where to put the packed file. Path specifies the path of the packaged file, filename specifies the filename after the package. Combined, the packaged files are in the dist directory
bundle.js
- Entry is a packaged entry file that tells WebPack which file to pack
-
Do a configuration under script in package.json:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack" }, Copy the code
-
Run NPM run build directly, and Node will automatically execute webpack, and you’ll see the generated JS file (only one) in the dist directory. Put index.html in your browser, and you’ll see what it looks like.
More than that
As you can see from the example above, with WebPack, we solved a variety of problems that we encountered in the traditional approach. Of course, Webpack can do much more than that. For example, when writing code, you might also have these requirements:
- Code conversion: compile TypeScript to JavaScript, COMPILE SCSS to CSS, etc.
- File optimization: compress JavaScript, CSS, HTML code, compress merged images, etc.
- Code segmentation: Extract the common code of multiple pages, extract the first screen without executing part of the code to make it asynchronously recorded in.
- Module consolidation: In a modularized project, there are many modules and files that need to be grouped into a single file by building functionality.
- Automatic refresh: Listens for local source code changes and automatically rebuilds and refreshes the browser.
- Code validation: Verifies compliance with specifications and unit tests before submitting code to the repository.
- Automatic release: After the code is updated, the automatic build releases the code online and transfers it to the release system.
We needed a tool to help us solve these problems and complete the build process. The purpose of the build tool is to make it easier to write code with newer features without worrying too much about browser compatibility. This allows us to save a lot of mechanical repetitive work, such as the browser will automatically refresh after modifying the code, and improve our development efficiency.
Of course, there were plenty of great build tools before WebPack, such as Grunt, gulp, etc. It is fair to say that WebPack is the most popular build tool of the day. Webpack is powerful not only in itself, but also in the many webPack-based plug-ins that provide a powerful ecosystem. There’s a lot more webPack can do, and we’ll continue to learn that step by step.