Abstract: Webpack introductory tutorial.
- Can’t learn Webpack? Look at this article!
- Author: MudOnTire
FundebugReproduced with authorization, copyright belongs to the original author.
Webpack has been popular for a long time, but many students are still confused when using Webpack, seeing so many documents, various configurations, various loaders, plugins immediately confused. I was no exception, so much so that FOR a long time I was only half-understanding of Webpack. But webpack was a hurdle we had to cross in order to continue to do a good job on the front end. It wasn’t that hard to master WebPack, but we just didn’t find the right way. This article is my own experience in learning webpack, for your reference.
What is Webpack?
In a word: Webpack is a Module bundler. The key words are “module” and “package”. What is a module? If file 1 needs to use some of the methods or variables of file 2, file 1 must be loaded after file 2. With the increase of the project, the dependency relationship between JS files is more and more complex, and the maintenance is more and more difficult. Such a dilemma drives front-end engineers to constantly explore new development mode, from the backend, APP development mode we get inspiration, why not introduce the concept of “module” so that JS files can reference each other? For module 1 to use the functionality of module 2, you simply need to explicitly refer to module 2 in that module 1, without worrying about their order. Based on this idea, CommonJS and AMD specifications were created, and then there were front-end module loading tools like require.js, System.js, and Node’s module system, until the now popular ES6 Module.
The introduction of modules solves the problem of dependent references between files, while packaging solves the problem of too many files. When a project grows into thousands of modules, a browser that has to load so many files can slow down page loading. Bundler can bundle multiple related files together to dramatically reduce the number of files and improve page loading performance. Providing modular development and compilation and packaging capabilities is at the heart of WebPack, and many other features are built around them.
The core concept
Module (Module)
For WebPack, a module is not just a javascript module; it contains any type of source file, from images to fonts to JSON files. Webpack supports referencing modules in the following ways:
- ES2015 import method
- CommonJs require () method
- AMD
define
和require
grammar - @import syntax in CSS /sass/ LESS files
url(...)
and<img src=... >
Image path in
Dependency Graph
A dependency diagram is an internal logical diagram that WebPack recursively generates based on the dependencies between each module. With this dependency diagram, WebPack can use a steed to package all required modules into a bundle.
Entry
The starting file for plotting dependencies is called Entry. The default entry is./ SRC /index.js, or we can configure it in the configuration file. The value can be one or multiple entries.
Single entry:
module.exports = {
entry: './src/index.js'
}
Copy the code
or
module.exports = {
entry: {
main: './src/index.js'}};Copy the code
Multiple entries, one chunk
We can also specify multiple independent files as entries, but pack them into a chunk. This method is called multi-main Entry. We need to pass in an array of file paths:
module.exports = {
entry: ['./src/index.js'.'./src/index2.js'.'./src/index3.js']}Copy the code
However, this method is not recommended because of its limited flexibility and scalability.
Multiple entries and chunks
If there are multiple entries and each entry generates the corresponding chunk, we need to pass object:
module.exports = {
entry: {
app: './src/app.js'.admin: './src/admin.js'}};Copy the code
This method has the best flexibility and extensibility, and supports merging with other partial configurations. For example, the development environment and production configurations are separated, and the common configuration is separated, and the environment configuration and the common configuration are combined when running in different environments.
Output = Output
Where there is an entrance, there is an exit. As the name implies, an export is the output that WebPack completes, and output defines the path and file name for the output. The default output path for Webpack is./dist/main.js. Similarly, we can configure output in the configuration file:
module.exports = {
entry: './src/index.js'.output: {
path: __dirname + '/dist'.filename: 'bundle.js'}};Copy the code
Multiple entries
When there are multiple entries and one entry should correspond to an output, the file name for the output needs to be substitutions to ensure that the file name is unique, such as using the name of an entry module:
module.exports = {
entry: {
app: './src/app.js'.search: './src/search.js'
},
output: {
filename: '[name].js'.path: __dirname + '/dist'}}Copy the code
The bundle files app.js and search.js are eventually generated under the./dist path.
Loader
Webpack itself only supports loading JS and JSON modules, and the idea behind Webpack is that all files can be referenced and loaded to generate dependency diagrams, so loader comes in. Loader enables Webpack to handle other types of files (such as images, font files, XML). We can define a loader in a configuration file like this:
webpack.config.js
module.exports = {
module: {
rules: [{test: /\.txt$/.use: 'raw-loader'}}};Copy the code
Test defines the file or file type to be converted, and use defines the type of the Loader to convert the file. This configuration tells Webpack that when it encounters a reference to a TXT file (using require or import), it uses raw-loader to convert the file before packaging it into the bundle.
There are also various types of loaders, such as CSS-loader for loading CSS files, file-loader for loading image and font files, htMl-loader for loading HTML files, babel-loader for converting the latest JS syntax into ES5, and so on. See Webpack Loaders for a complete list.
Plugin (Plugin)
Plugin and Loader are two confusing and ambiguous concepts. Loader is used to convert and load specific types of files, so the execution layer of Loader is a single source file. Plugin can realize more powerful functions. Plugin can monitor key events in the process of Webpack processing and deeply integrate into the compiler of Webpack. It can be said that the execution level of Plugin is the whole construction process. Plugin system is the backbone of Webpack, and Webpack itself is built based on Plugin system. Webpack has rich built-in plug-ins and external plug-ins, and allows users to customize plug-ins. The official list of plug-ins has these.
Unlike loader, to use plugin we must first reference the plugin, for example:
const webpack = require('webpack'); // Used to reference the webPack built-in plug-in
const HtmlWebpackPlugin = require('html-webpack-plugin'); // External plug-ins
module.exports = {
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'}})];Copy the code
Fundebug is a very useful BUG monitoring tool
practice
Now that we understand the basic concepts of WebPack, we can deepen our understanding through practice. Next, we’ll use WebPack to build a simple React scaffolding.
Create a project
First create the React-Webpack-starter project and initialize it with NPM init.
Install dependencies
Install the react
npm i react react-dom
Copy the code
Webpack installation is related
npm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin style-loader css-loader
Copy the code
After webpack-CLI is installed, you can run the webpack command on the CLI. Webpack-dev-server provides a simple Web server, and automatically executes webpack compilation and automatically refreshes the browser after modifying files, eliminating repeated manual operations. Html-webpack-plugin is used to automatically generate index.html files and automatically add references to bundles in index.html. Style-loader and CSs-loader are used to load CSS files.
Install Babel related
React uses es6 syntax such as class and import. In order to improve browser compatibility, we need to use Babel conversion.
npm i -D @babel/core @babel/preset-env @babel/preset-react babel-loader
Copy the code
@babel/core is the core module of Babel, which contains the core functions of Babel. @babel/preset-env supports conversion of ES6 and updated JS syntax, and plugins loaded can be selected according to compatible browser types to simplify generated code; @babel/preset-react contains the plugin needed for Babel to convert react; Babel-loader is the Babel loader for WebPack.
Configuration webpack
Create a new webpack.config.js file under the project root directory as follows:
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js'.output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [{test: /\.js$/.exclude: /node_module/.use: 'babel-loader'
},
{
test: /\.css$/.use: ['style-loader'.'css-loader'] // Pay attention to the order, the execution order is the opposite of the order}},plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'}})]Copy the code
HtmlWebpackPlugin uses a customized template to generate HTML files. The content of the template is as follows:
./src/index.html
<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>My React App</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
Copy the code
Configure the Babel
Create a new. Babelrc file under the project root and configure our installed two Babel preset files:
.babelrc
{
"presets": [
"@babel/preset-env"."@babel/preset-react"]}Copy the code
Generate the React application root node
./src/index
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(<App />, document.getElementById('app'));
Copy the code
./src/component/App.js
import React, { Component } from 'react';
import './App.css';
export default class App extends Component {
render() {
return (
<div>
my react webpack starter
</div>)}}Copy the code
./src/components/App.css
body{
font-size: 60px;
font-weight: bolder;
color: red;
text-transform: uppercase;
}
Copy the code
configurationpackage.json
Finally, add two scripts to the package.json file to run the development server and package:
package.json
"scripts": {
"start": "webpack-dev-server --mode development --open --hot"."build": "webpack --mode production"
}
Copy the code
Note that we have enabled module hot update (HMR) for Webpack-dev-server to further improve our development efficiency.
The react scaffolding is now up and running.
Is it not as difficult as expected? Of course, WebPack has a lot of other features and features to master, I hope that after referring to this article you further study more smoothly 😊.
Demo address: github.com/MudOnTire/….
Finally, I recommend Fundebug, a very useful BUG monitoring tool
About Fundebug
Fundebug focuses on real-time BUG monitoring for JavaScript, wechat applets, wechat games, Alipay applets, React Native, Node.js and Java online applications. Since its official launch on November 11, 2016, Fundebug has handled over 1 billion error events in total, and paid customers include Sunshine Insurance, Walnut Programming, Lychee FM, Zhangmen 1-to-1, Weimai, Qingtuanshe and many other brand enterprises. Welcome to try it for free!