Webpack introduction
Webpack itself is a module packaging tool that packages scattered module codes into the same JS file. For environment-compatible codes in the package, they can be compiled and installed through the module loader during the packaging process. Meanwhile, Webpack also has the ability of code splitting In the application of our code as we need to pack Solved in the application of all the module code packaged together to produce a larger file problem of application of loading process When will the first running modules must be packaged together For other modules separately store When we need the asynchronous loading of these modules again Supports modular loading of any type of file
The installation
yarn add webpack webpack-cli --dev
Copy the code
The configuration file
- Create a webpack. Config. Js
- It is a file that runs in the Node environment
- Control package input/output directory
const path = require('path')
module.exports ={
entry:'./src/index.js'.// Pack the entry
output: {// Package and output the directory
filename:'bundle.js'.path:path.join(__dirname,'output') // It must be an absolute path or an error is reported}}Copy the code
Webpack results run principle
bundle.js
- The self-calling argument to a function is an array and each element is a function corresponding to a module in the source code which means that each module is wrapped around each function to achieve private scope
Work entry function
- Defines a module that has been loaded by the object cache
- Webpack_require_ defines a function to load modules
- Some utility functions are mounted in webpack_require
- Return webpack_require starts loading the module
Webpack_require execution procedure
- Check in the cache to see if it has been loaded
- No cache defined object attributes include moduleId L export
- Call the moduleId function, execute the contents of the function, and assign the exported contents of module.export to the export object
Webpack4 adds the use of working mode
Production mode
- Use the default
- Help us compress our code
yarn wepack --mode production
Copy the code
Development pattern
- Optimize our packaging speed and easy debugging
yarn webpack --mode development
Copy the code
None mode
- Running a package in its raw state does nothing to it
- In addition, you can configure the packaging mode by setting the mode property in the configuration file
yarn webpack --mode none
Copy the code
In addition to the command line, it can be used directly in the configuration file
const path = require('path')
module.exports ={
mode:'production'.entry:'./src/index.js'.output: {filename:'bundle.js'.path:path.join(__dirname,'output') // It must be an absolute path or an error is reported}}Copy the code
Loader
introduce
- Focus on resource module loading
- Core features of WebPack
- Any type of resource can be loaded with loader
- Work with resource modules as JS code
- Webpack packs JS code by default and other files need to use the loader
Css loader
- Packing CSS files
The installation
yarn add css-loader --dev
yarn add style-loader --dev
Copy the code
configuration
const path = require('path')
module.exports ={
mode:'none'.entry:'./src/main.css'.output: {filename:'bundle.js'.path:path.join(__dirname,'dist')},// Load the configuration of resource rules for other resource modules
// Each rule object requires two attributes
//text Regular expressions are used to match file paths during packaging
//use Loader used by matched files Executes the last loader first
module: {rules:[
{
test:/.css$/,
use:[
'style-loader'.'css-loader'}]}}Copy the code
The working principle of
• CSS-loader converts CSS files into packaged modules and pushes THE CSS code into bundle.js module arrays that are provided by modules within CSS-LoDash without using this array Style-lodash Appends the CSS – loDash result to the page as a style tag
filer-loader
- Image font…. In the form of JS
- The installation
- yarn add file-loader –dev
- case
- Import the image and add it to the page
module.export = {
entry:'main.js'.output: {filename:'bundle.js'.path:path.join(__dirname,'dist'),
publicPath:'dist/'.// The file path is in the project path by default, and the package is in the dist directory so that the browser does not see the effect
},
module: {rules:[
{
test:'/.png/'.use: ['file-loader'] // here
},
{
test:'/.css/'.use: ['style-loader'.'css-loader'}]}}Copy the code
URL resource loader
introduce
- In addition to file-loader, you can also use the URL resource loader
- A Data URL is a special URL protocol where a traditional URL requires that the server must have a file and then request the corresponding address to get the file on the server whereas a Data URL directly represents the content of a file using a URL that doesn’t send anything HTTP requests are simply text containing the contents of the file
format
Take this code for example
The browser will parse out that this is an HTML file with utF-8 encoding and h1 tag content
If the image or font is a binary type that cannot be represented by text, the file can be base64 encoded by the image and the result of base64 encoded as the image content
The installation
yarn add url-loader --dev
Copy the code
Use advice
It is suitable for resources with relatively small volume. If the volume is relatively large, the packaging result will be greatly affected, thus affecting the running speed
- Best practices
- Small files use data urls to reduce the number of requests
- Large files are stored separately by file-loader to improve loading speed
- If the limit range exceeds the size of the range, file-loader is used
{
test:/.png$/,
use:{
loader:'url-loader'.options: {limit :10*1024 // Store a file smaller than 10KB to the URL}}}Copy the code
- Files larger than 10kb are stored separately
- Less than 10KB is converted to data URL embedded code
Note:
File-loader must be installed
babel-loader
- Webpack is a packaging tool that handles only import and export and the corresponding transformations but not other es6 features
Installation:
yarn add babel-loader @babel/core @babel/preset-env --dev
Copy the code
configuration
{
test: /.js$/,
use: {
loader: 'babel-loader'.options: {
presets: ['@babel/preset-env']}}},Copy the code
How webpack imports resources
- Three import modes are supported
- ESmodule standard import statement
Commonjs standard require
AMD standard define function and require function
- Pay attention to
- Not mixing these standards unless necessary will significantly reduce the maintainability of your project
- The import HTML module is a string that needs to be accepted
- Modules can also be loaded in the following ways
- The @import directive and URL function in the style code
- Image tag SRC attribute in HTML code
- The HTMl-loader must be installed when importing HTML modules into the entry file JS
- The HTML default handles img SRC attributes triggering other tag attribute packaging needs to be configured
html-lodaer
module: {rules:[
{
test:'/.html/'
use:[
loader:'html-loader'.options: {attr: ['img:src'.'a:href']}]}Copy the code
Webpack characteristics
- All resources that need to be referenced in the code will be found by Webpack and processed according to the reference configuration and different loaders to package the output directory of the processed results. Webpack uses this feature to achieve project modularization
- The core working principle and process of Webpack packaging
- There’s a lot of code and resource files scattered around the project and Webpack will find js files based on our configuration as the entry point for packaging and then follow our entry point to parse the modules that the code needs based on statements like import and export that appear The dependencies for each resource module are resolved separately to form the dependency count of all files used in the entire project. Webpack then recurses this dependency count to find the file configured for each node and then finds the loader corresponding to the module according to the rules property in the configuration file and gives the loader to load the module Finally, the loaded results are put into bunner.js to achieve the packaging of the entire project
Develop your own loader
- Each loader needs to export a function that processes the loaded resource. The input is the content of the file to be loaded. The output is the processed result
- concept
- Loader is responsible for converting resource files from input to output
- You can pass the loader to the next loader
- standard
- The final return value of the loader must be a piece of JS code
- If the js code is not in the packed JS module, an error will be reported
- Allows eventual conversion to JS code with multiple Loaders like pipes
Example: Create markdom-loader
• This function takes input and processes it and outputs the result as a return value
// Download and import marked third-party modules to convert the content to HTML tags
const marked = require('marked')
module.exports= source= >{
const html = marked(source)
// Convert HTML to a string
return `export defalut The ${JSON.stringify(html)}`
// Pass the returned result to the next loader
// return html
}
Copy the code
loader:[
'./markdowm-loader'.'html-loader'
]
Copy the code
Webpack plugin mechanism plugin
- The plugin mechanism is another core webPack mechanism
- role
- Enhance WebPack automation capabilities
- Solve other automation tasks except for loading loader resources
- For example,
- Clear the dist directory before packaging
- Copy static files to the output directory
- Zip the package and print the code
- Common plug-in
- Most plug-in modules export a class and use it to create instances of the type and place them in the plugins array
clean-webpack-plugin
- Deconstruct the imported plug-in and create the instance object
- Clear the dist directory before each package
- The installation
- yarn add clear-webpack-plugin –dev
- The import
- import { ClearWebapckPlugin } from ‘clear-webpack-plugin’
A plugin adds elements to an array
plugins: [new CleanWebpackPlugin()
]
Copy the code
html-webpack-plugin
- Writing HTML in a hard-coded manner will result in the inability to ensure that the path reference is correct after going live and the need to manually modify the HTML reference path when the entry file of the configuration file changes
- Automatically generate an HTML file that uses the bundle.js package and put it in the same directory as you publish the dist directory once you go live and the HTML references to the bundle are dynamically injected and you don’t have to manually hard code to make sure that the path references are normal
- The default exported file type does not need to be deconstructed
- The installation
- yarn add html-webpack-plugin –dev
- The HTML title is implemented by modifying the attributes of htmlwebpackPublic
- If you need to customize the HTML file
- Copy a template file from a template file
- Create multiple htmlWebPackPlugin instances into plugins properties when multiple page files are needed
- Problem: The HTML file could not be found in the startup project
- Modify the publicPat attribute to change the HTML directory to the current directory
plugins:[
new htmlWebpackPlugin({
title:' ' // The HTML title
meta: {viewPort:'width=device-width'
},
// Customize the template content
template:'./src/index.html'
})
// Generate multiple HTML files
new htmlWebpackPlugin({
filename:'about.html'})]Copy the code
copy-webpack-plugin
- Use a background
- Enter the static file Plugin folder into dist
- Do not use this plug-in during development
new CopyWebpackPlugin({
// From that path to that path
patterns: [{from: "public".to: "public"},]})Copy the code
Develop your own plug-ins
- Implementation of plug-in mechanism
-
The hook mechanism is often seen in software development. The hook mechanism is the event mechanism in the Web. There are many links in the webPack work to facilitate extension of the plug-in The ability of webpack
-
The requirement that a plug-in must be a function or an object that contains an Apply method is usually done by creating a type, adding an Apply method to the type, and then using the method by creating an instance
-
This is an extension to the declaration cycle mount function packaged in Webpack
-
class myPlugin{
// Compiler registers information
apply(compiler){
//compilation
compiler.emit.tap('myplugin'.(compilation) = >{
// Iterate over the module
for(let name for compition){
if(name.endWidth('.js')) {// Get the text content
const content = compilation.assets[name].source()
// Replace the comments in the text
const widthoutComents = content.replace(/\/\*\*+*\/g,'') // compilation. Assets [name] ={source: () => widthoutComents, size:() => widthoutComents.length } } } }) } }Copy the code
Webpack thought
- Webpack recommends introducing any resources that your current code needs in JS because it’s not the application that needs the resources, it’s the code you’re writing that needs them
- JavaScript drives the entire front-end application
- Logical and reasonable, JS needs a variety of files to achieve the corresponding functions
- Make sure that resources are available when you go live and that every file is necessary
Preview the next webpack results for optimizing and improving the packaging experience