Essentially, WebPack is a static Module Bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a dependency graph that contains every module the application needs, and then packages all of those modules into one or more bundles.
Frameworks such as VUE and React and modular programming make projects cleaner and easier to maintain. For page loading, more module files mean more requests and slower page loading. Each framework usually has its own syntax and file types. Webpack through the loader to deal with the JavaScript file, the module packaged into one or more static resource files (js, CSS, JPG | PNG, etc.) and optimize it.
Install WebPack
In the project folder path, install webPack and webpack- CLI:
npm install webpack webpack-cli --save-dev
Copy the code
Using WebPack for packaging is set in the configuration file, the default configuration file is webpack.config.js,
You can also specify a configuration file in package.json :(change webpack.config.js from the image above to aa.js)
Ii. Core concepts
1. Entry and Output
Entry specifies the packaging entry of the WebPack. From the entry, you will find dependencies, recurse to form a dependency tree, and finally iterate through the dependencies to generate the packaged file.
Correspondingly, output specifies where WebPack outputs the package files it creates and how to name them.
Webpack packaging is divided into single entry and multiple entry.
Single entry. Entry is a string of the relative address of the entry file. Output is an object with two fields: PATH and filename.
As shown in the following figure, the package will generate a JS file, bundle.js in the dist directory.
Multiple entries: An entry is an object, and each field is an entry. The filename of output is “[name].js”. Placeholders are used to ensure that the output js files correspond to the entry JS files one by one.
As shown in the following configuration, the package generates two JS files (the same number of entries in Entry), index1.js and test1.js in the dist directory
2, loader,
Webpack itself only understands javascript and JSON, and loader can convert all types of files into valid modules that WebPack can handle and add to the dependency graph for packaging processing. Loader itself is a function that accepts the source file as an argument and returns the result of the conversion.
Loader is configured in the Rules field of the Module object. Rules is an array that allows you to configure multiple Loaders. Each loader has two properties:
Test: matches the files that should be converted by the corresponding Loader. The value is a regular expression. Use: indicates the loader that should be used to convert source files.Copy the code
In daily development, the following loaders are commonly used:
- Babel-loader: converts new JS feature syntax such as ES6 and ES7
- Css-loader: supports loading and parsing of. CSS files
- Less-loader: converts less files to CSS (similar to sass-loader/stylus-loader)
- Style-loader: generates a style tag containing the final parsed CSS code and puts it in the head tag
- Postcss-loader: further processes CSS files, such as adding browser prefixes and compressing the CSS
- Url-loader: processes files such as images and font ICONS
Take csS-Loader and style-loader as an example:
Webpack. Config. Js configuration:
module.exports = {
entry: "./src/index.js",
output: {
path: path.join(__dirname,"/dist"),
filename: "bundle.js"
},
module:{
rules:[
{
test: /\.css$/,
use: ['style-loader','css-loader']
}
]
},
}
Copy the code
(1) index. HTML
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, </div> <script SRC ="./dist/bundle.js"></script> </body> </html>Copy the code
(2) index.js (csS-loader makes it possible to parse CSS files in js files, otherwise syntax errors will be reported)
import "./css/index.css"
Copy the code
(3)index.css
body{
color: red;
}
Copy the code
The final structure of the generated document :(the style-loader generates a style tag containing the final parsed CSS code and puts it in the head tag. Without the style tag generated by the style-loader, the styles in the index. CSS will not apply to the document.)
It is worth noting that a matching rule can be configured to use multiple Loaders, that is, a module file can be converted by multiple Loaders, and the execution sequence of loaders is from right to left.
3, the plugins
Loader preprocesses the source files, and the plugin is used to build the package, such as file compression, resource management, and so on.
Plugins are configured in the plugins array, and a plugin is added to the plugins array whenever it needs to be used.
Plugins that I often use include:
- Html-webpack-plugin: Creates an HTML file to host the output bundle
let HtmlWebpackPlugin = require('html-webpack-plugin'); New HtmlWebpackPlugin({template: 'index.html', // use the template file, not limited to the HTML suffix filename: // The generated HTML file (in the dist directory) hash: true, // will add the hash string after the bundle.js or extracted.css file. Minify: {removeComments: true, // remove the HTML collapseWhitespace comment: true, // remove the whitespace and newline in the HTML, so that the entire file is collapsed in one line}})Copy the code
Will generate index.html at 2 from index.html at 1, and add a reference to bundle.js in index.html at 2:<script src="bundle.js? 29a7f233afce83fb4104"></script>
- Clean-webpack-plugin: cleans the build directory. Solves the problem of dist directory files accumulating as file hash values are output
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
new CleanWebpackPlugin()
Copy the code
- Copy-webpack-plugin: copies files or directories, such as static folders.
new CopyWebpackPlugin({
patterns: [
{
from: __dirname+'/src/static',
to: __dirname+'/dist/static'
}
]
})
Copy the code
- Mini-css-extract-plugin: Decompress the CSS modularized into a separate file and create a CSS file for each JS file containing the CSS. (Style-loader writes the CSS file to the packaged HTML page with inline style tags; The mini-css-extract-plugin is a direct link to the js file. If multiple CSS files are imported into the js file, the mini-CSs-extract-plugin will be merged into a single CSS file. The contents of the mini-CSs-extract-plugin are in the order of the import of the JS file.
const MiniCssExtractPlugin = require('mini-css-extract-plugin') module:{ rules:[ { test: /\.css$/, use: [MiniCssExtractPlugin. Loader, 'CSS - loader'] / / remove style - loader, For MiniCssExtractPlugin loader},]}, plugins: [new MiniCssExtractPlugin ({filename: 'style/style.css' // defaults to main.css in dist directory)]Copy the code
- Optimism-css-assets – Webpack-plugin: Compress the CSS file and optimize the CSS structure
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
new OptimizeCSSAssetsPlugin()
Copy the code
- Uglifyjs-webpack-plugin: compressions JS code.
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') new UglifyJsPlugin({ uglifyOptions: { compress: {drop_debugger: true, drop_console: true, // delete console automatically}}, sourceMap: false})Copy the code
ERROR in bundle.js from uglifyjs Unexpected token: Operator «>», so using this plug-in requires using Babel-Loader to convert ES6 to ES5.
When mode is Production, UglifyJsPlugin is automatically started.
4, mode
Mode specifies the current build environment. It can be production, development, or None. The default is Production. Mode can be set using webPack’s built-in functions, as shown below.
-
Development: Enable NamedChunksPlugin and NamedModulesPlugin.
-
Production: Enable FlagDependencyUsagePlugin FlagIncludedChunksPlugin, ModuleConcatenationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and UglifyJsPlugin.
-
None: indicates that no optimization option is enabled.
Mode can be set in the configuration file:
module.exports = {
mode: 'development'
};
Copy the code
It can also be set from the command line:
webpack --mode development
Copy the code