The document
Webpack is used to compile JS modules, commonly known as “project engineering” tools.
For details, see the English and Chinese documents.
The installation
If you use a quick build tool such as scaffolding (VUe-CLI), it’s usually integrated with Webpack and some basic configuration.
Version information
First view the version information of Webpack through NPM.
$NPM info webpack / / [email protected] | MIT | deps: 23 | versions: 625 / / executable / / bin: webpack / / / / all version dist - tags: Latest: 4.41.2 Legacy: 1.15.0 next: 5.0.0-beta.9 // webpack-2: 2.7.0 webpack-3: 3.12.0Copy the code
We use the latest version, WebPack4, by default. Yarn is recommended instead of NPM.
Start the Webpack
Using the local path
Local boot:
$ ./node_modules/.bin/webpack
Copy the code
Run the NPX command
Starting Webpack with NPX automatically looks for executable files in your directory.
Note: Some conditions may be unstable on Windows, such as a space in the path of installing Node.
$ npx webpack
Copy the code
Webpack defaults to output in the dist directory of the current directory. This is done through the integrated loader Babel-loader.
Optimize build (build)
Using a quick script, the dist directory is emptied and rebuilt on each build.
Mac/Linux
{
"script": {
"build": "rm -rf dist; webpack"}}Copy the code
Windows
{
"script": {
"build": "rm -rf dist && webpack"}}Copy the code
Using the command
$ yarn build
Copy the code
The use of plug-in
Use the clean-webpack-plugin instead.
Installation:
$ yarn add clean-webpack-plugin
Copy the code
Configuration plug-in:
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js'.print: './src/main.js'
},
plugins: [
new CleanWebpackPlugin(['dist'])]}; }Copy the code
Commonly used configuration
The translation mode in the configuration file is set with a warning by default.
Paths and Patterns
Create a configuration file.
$ touch webpack.config.js
Copy the code
Configuration:
const path = require("path");
module.exports = {
// Translation mode: development mode/production mode
mode: "development"./ / input source
entry: "./src/index.js"./ / output
output: {
/ / file name
filename: "main.js".// Output path
path: path.resolve(__dirname, "dist")}}; Cache requirement file nameCopy the code
Cache requirement file name
You can set it to generate a string containing an MD5 hash to insert the file name for HTTP caching.
module.exports = {
...
output: {
filename: "main.[contenthash].js"}};Copy the code
Automatic HTML generation
Use the HTML-webpack-plugin.
$ yarn add html-webpack-plugin
Copy the code
Configuration:
module.exports = {
...
plugins: [
new HtmlWebpackPlugin({
title: 'Title'.favicon: require('./favicon.ico'),
template: 'src/assets/index.html'})]};Copy the code
To use a custom title, you need to configure it in HTML:
<head>
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
Copy the code
Import and automatically generate CSS
Using the loader
$ yarn add css-loader style-loader
Copy the code
role
- Css-loader is used to immediately process and read into the JS file if it finds any file ending in.css.
- Style-loader is used to insert unique content into the page as a style tag in an HTML file.
configuration
module.exports = {
entry: './src/index.js'.output: {
filename: 'main.js'.path: path.resolve(__dirname, 'dist')},module: {
rules: [{test: /\.css$/,
use: [
'style-loader'.'css-loader'}]}};Copy the code
Separate and extract into CSS files
Use the mini-CSS-extract-plugin to package CSS files and extract CSS styles from JS files into separate CSS files.
The installation
$ yarn add mini-css-extract-plugin
Copy the code
Configuration:
+ const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// all options are optional
filename: '[name].[contenthash].css'.chunkFilename: '[id].[contenthash].css'.ignoreOrder: false.// Enable to remove warnings about conflicting order}),].module: {
rules: [{test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it uses publicPath in webpackOptions.output
publicPath: '.. / '.hmr: process.env.NODE_ENV === 'development',}},'css-loader',],},],},};Copy the code
This plug-in regenerates the CSS file in the dist directory and inserts it in the HTML as a link tag. All imported CSS files are consolidated into one file, and the contents are sorted according to the order in which they are imported.
Advanced configuration
Describes some advanced Webpack configurations. First, a little digging.
Plug-ins and loaders
There are two main ways to use and expand Webpack: loading plug-ins or installing loaders.
The definition and difference between the two
- The difference in intention.
- The loader is mainly used to load resource files, and plug-ins are used to enhance and extend functions.
- Of course loader also extends Webpack in a disguised way, but it focuses more on converting files.
- Plugins are more versatile than just loading resources.
- A loader must load one file into another, while a plugin may merge multiple files into a single file.
The introduction of SCSS
Import.scss files.
Note: Use Dart-sass instead of Node-sass because the latter is outdated and difficult to install.
The installation
$ yarn add sass-loader dart-sass
Copy the code
Syntax for SCSS:
$color: red;
body{
color: $color;
}
Copy the code
The following shows the chain invocation of sass-loader, CSS-loader, and style-loader.
Configuration (Sass-loader uses Node-sass by default, you need to change it to Dart-sass) :
module.exports = {
...
module: {
rules: [{test: /\.scss$/,
use: [
"style-loader".// Generate JS strings as style nodes
"css-loader".// Convert CSS to CommonJS modules
//"sass-loader" compiles sass to CSS. If only this line is written, Node sass is used by default
{
loader: "sass-loader".options: {
implementation: require('dart-sass'}},]}]}}Copy the code
The introduction of less
Import.less files.
This module requires Node V6.9.0 + and Webpack V4.0.0 +.
Installation:
$ yarn add less-loader less
Copy the code
Less syntax:
@color: red;
body{
color: @color;
}
Copy the code
The following shows the chain invocation of less-loader, CSS-loader, and style-loader. Configuration:
module.exports = {
...
module: {
rules: [{test: /\.less$/,
use: [
"style-loader".// Generate JS strings as style nodes
"css-loader".// Convert CSS to CommonJS modules
"less-loader".// Compile Less to CSS]},]}}Copy the code
The introduction of stylus
Import.styl files.
The installation
$ yarn add stylus-loader stylus
Copy the code
Stylus syntax:
setColor = red;
body{
color: setColor;
}
Copy the code
configuration
module.exports = {
...
module: {
rules: [{test: /\.less$/,
use: [
"style-loader".// Generate JS strings as style nodes
"css-loader".// Convert CSS to CommonJS modules
"stylus-loader".// Compile the Stylus into CSS}]}}Copy the code
Using the file – loader
The file-loader can convert a file to a file path according to the require path for loading purposes.
The installation
$ yarn add file-loader
Copy the code
configuration
module.exports = {
module: {
rules: [{test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader'.options: {
context: 'project'.publicPath: 'assets',},},],},}Copy the code
Browse – Develop quickly
Using Webpack-dev-server, you can quickly build a simple Web server that reads files in the dist directory and updates reloads in real time.
The installation
$ yarn add webpack-dev-server
Copy the code
configuration
module.exports = {
entry: {
app: './src/index.js'.print: './src/print.js'
},
devtool: 'inline-source-map'.devServer: {
contentBase: './dist'}};Copy the code
Adding script Commands
{
"script": {
"start": "webpack-dev-server --open"}}Copy the code
— Open: automatically opens the browser.
Lazy loading
Lazy loading, or loading on demand, is a great way to optimize a web page or application.
This approach essentially takes your code away at some logical point, and then references or is about to reference a new block of code as soon as something is done. This speeds up the initial loading of the application and reduces the overall volume, since some code blocks may never be loaded.
Implementation approach
Load the file as a function with import, and get a promise, a success or failure callback.
The sample
Create files that need to be loaded on demand.
$ touch src/lazy.js
Copy the code
Define modules in HTML
<body>
<div id="lazy-load"></div>
</body>
Copy the code
index.js
onst div = document.getElementById('lazy-load')
const button = document.createElement('button')
button.innerText = 'I am Lazy-Load'
button.onclick = () = > {
const promise = import('./lazy')
promise.then((module) = >{
module.default()
},() = >{
console.log('Error')
})
}
div.appendChild(button)
Copy the code
lazy.js
export default function lazyModule() {
console.log('This is a lazy loading module.')
alert('This is a lazy loading module.')}Copy the code