Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to master webpack

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to master webpack". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is webpack?

To sum up: webpack is a module packaging tool (module bundler). The focus is on the two keywords "module" and "packaging". What is a module? We review the previous front-end development, js files are statically introduced through script tags, and there is no strong dependency between js files. If file 1 wants to use some of the methods or variables of file 2, file 1 must be loaded after file 2. With the growth of the project, the dependency relationship between js files becomes more and more complex, and the maintenance becomes more and more difficult. This dilemma drives front-end engineers to constantly explore new development patterns, and we get inspiration from the back-end and app development patterns. Why can't we introduce the concept of "module" so that js files can reference each other? For module 1 to use the functions of module 2, you only need to explicitly reference module 2 in module 1 without worrying about their order. Based on this idea, the CommonJS and AMD specifications were created, and then there were front-end module loading tools such as require.js and system.js and the module system of node, until now the popular es6 module.

The introduction of the module solves the problem of dependent references between files, while packaging solves the problem of too many files. When the scale of the project increases and the number of modules is thousands, if the browser wants to load so many files, the page loading speed is bound to be affected, and bundler can package multiple related files together to greatly reduce the number of files and improve web page loading performance. Providing modular development and compilation and packaging capabilities is the core of webpack, and many other functions revolve around them.

Core concept

Module (module)

For webpack, a module is not just a javascript module, it includes any type of source file, whether it's pictures, fonts, or json files. Webpack supports referencing modules in the following ways:

ES2015 import method

CommonJs require () method

AMD define and require syntax

@ import syntax in the css/sass/less file

Url (...) And

The picture path in

Dependency Graph (dependency Graph)

The so-called dependency graph is an internal logic graph recursively generated by webpack according to the dependency relationship between each module. With this dependency graph, webpack can follow the clues to find and package all the needed modules into a bundle file.

Entry (entrance)

The starting file for drawing dependency diagrams is called entry. The default entry is. / src/index.js, or we can configure it in the configuration file. Entry can be one or more.

Single entry:

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

Or

Module.exports = {entry: {main:'. / src/index.js'}}

Multiple entry, one chunk

We can also specify multiple separate files as entry, but package them into a chunk, which is called multi-main entry, and we need to pass in an array of file paths:

Module.exports = {entry: ['. / src/index.js','. / src/index2.js','. / src/index3.js']}

However, the flexibility and expansibility of the modified method are limited, so it is not recommended.

Multiple entry, multiple chunk

If there is more than one entry and each entry generates a corresponding chunk, we need to pass in object:

Module.exports = {entry: {app:'. / src/app.js', admin:'. / src/admin.js'}}

This method of writing has the flexibility and expansibility of * * and supports merging with other local configurations (partial configuration). For example, separate the configuration of the development environment from the production, extract the common configuration, and merge the environment configuration and public configuration when running in different environments.

Output (Export)

When there is an entrance, there is an exit. As the name implies, an exit is the output packaged by webpack, and output defines the path and file name of 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'}}

The case of multiple entry

When there is more than one entry, one entry should correspond to one output. In this case, the output file name needs to be declared with the substitution character (substitutions) to ensure the uniqueness of the file name, such as using the name of the entry module:

Module.exports = {entry: {app:'. / src/app.js', search:'. / src/search.js'}, output: {filename:'[name] .js', path: _ _ dirname +'/ dist'}

Finally, two bundle files, app.js and search.js, are generated under the. / dist path.

Loader (loader)

Webpack itself only supports loading js and json modules, while the idea of webpack is to let all files be referenced and loaded and generate dependency graphs, so loader comes out. Loader enables webpack to handle other types of files (such as images, font files, xml). We can define a loader in the configuration file as follows:

Webpack.config.js

Module.exports = {module: {rules: [{test: /\ .txt $/, use: 'raw-loader'}]}}

Where test defines the file or file type that needs to be converted, and use defines the type of loader that converts the file. This configuration is equivalent to telling webpack that when it encounters a reference to a txt file (using require or import for reference), convert the file with raw-loader and then package it into bundle.

There are various other types of loader, such as css-loader that loads css files, file-loader that loads picture and font files, html-loader that loads html files, babel-loader that converts * JS syntax into ES5, and so on. For a complete list, please refer to webpack loaders.

Plugin (plug-in)

Plugin and loader are two confusing and vague concepts. Loader is used to convert and load specific types of files, so the execution level of loader is a single source file. The function that plugin can achieve is more powerful, plugin can listen to the key events in the process of webpack processing, deeply integrated into the compiler of webpack, it can be said that the implementation level of plugin is the whole construction process. Plugin system is the backbone of webpack, and webpack itself is also based on plugin system. Webpack has rich built-in plug-ins and external plug-ins, and allows users to customize plug-ins. These plug-ins are officially listed.

Unlike loader, we must first reference the plug-in to use plugin, for example:

Const webpack = require ('webpack'); / / used to reference the webpack built-in plug-in const HtmlWebpackPlugin = require (' html-webpack-plugin'); / / external plug-in module.exports = {plugins: [new webpack.HotModuleReplacementPlugin (), new HtmlWebpackPlugin ({template:'. / src/index.html'})]}

Practice

After understanding the basic concepts of webpack, we deepen our understanding through practice. Next, we use webpack to build a simple react scaffolding.

Create a project

First create the react-webpack-starter project and initialize it with npm init.

Installation dependency

Install react

Npm i react react-dom

Installation of webpack related

Npm I-D webpack webpack-cli webpack-dev-server html-webpack-plugin style-loader css-loader

After installing webpack-cli, you can execute webpack commands on the command line; webpack-dev-server provides a simple web server, and automatically performs webpack compilation operation and automatically refreshes the browser after modifying the file, eliminating repeated manual operations; html-webpack-plugin is used to automatically generate index.html files and automatically add references to bundle files in index.html; style-loader and css-loader are used to load css files.

Installation of babel related

Because the syntax of es6 such as class and import is used in react, in order to improve the browser compatibility of the website, we need to convert it with babel.

Npm I-D @ babel/core @ babel/preset-env @ babel/preset-react babel-loader

@ babel/core is the core module of babel and contains the core functions of babel; @ babel/preset-env supports the conversion of ES6 and updated js syntax, and you can select the loaded plugin according to the compatible browser type to simplify the generated code; @ babel/preset-react includes that plugin;babel-loader is webpack's babel loader needed for babel to convert react.

Configure webpack

Create a new webpack.config.js under the root of the project, 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 Plugins: [new HtmlWebpackPlugin ({template:'. / src/index.html'})]}

HtmlWebpackPlugin uses a custom template to generate html files. The template contains the following:

. / src/index.html

My React App

Configure babel

Create a new .babelrc file under the project root and configure the two babel preset we installed:

.babelrc

{"presets": ["@ babel/preset-env", "@ babel/preset-react"]}

Generate react application root node

. / src/index

Import React from 'react'; import ReactDOM from' react-dom'; import App from'. / components/App'; ReactDOM.render (, document.getElementById ('app'))

. / src/component/App.js

Import React, {Component} from 'react'; import'. / App.css'; export default class App extends Component {render () {return (my react webpack starter)}}

. / src/components/App.css

Body {font-size: 60px; font-weight: bolder; color: red; text-transform: uppercase;}

Configure package.json

* 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"}

Note that we have enabled webpack-dev-server 's module hot update feature (HMR) to further improve our development efficiency.

At this point, the simplest version of react scaffolding has been built. Let's run it to see the effect:

This is the end of "how to master webpack". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report