Webpack introduction and use

Webpack is a front-end modular packaging tool that performs static analysis based on module dependencies and then generates corresponding static resources for these modules according to specified rules. It mainly consists of four parts: entrance, exit, loader and plugins.

Webpack is currently the most popular front-end resource modular management and packaging tool. It can package many loose modules according to dependencies and rules into front-end resources suitable for production deployment. You can also code separate modules that are loaded on demand and load them asynchronously when they are actually needed. Through loader conversion, any form of resources can be regarded as modules, such as CommonJs module, AMD module, ES6 module, CSS, images, JSON, Coffeescript, LESS, etc.

The modules under devDependencies are the ones we need to use in development, such as gulp, compression CSS and JS modules. These modules are not needed after our project is deployed, so we can install them using -save-dev. Website: www.webpackjs.com/concepts/

The four concepts of Webpack

Entrance to the entry

Create a new project file, create a new webpack.config.js file in the directory, and process the project related files according to the configuration content in this configuration file. To write this file, you need to follow the commonJS specification. You can run it directly with the Git command webpack, or if it is a different name, run the webpack–config package filename command to pack it.

The entry point indicates which module WebPack should use as a starting point for building its internal dependency diagram. Once at the entry point, WebPack finds out which modules and libraries are (directly and indirectly) dependent on the entry point.

/ / webpack. Config. Js
module.exports = {
  entry: './path/to/my/entry/file.js'
};Copy the code

Export output

The Output attribute tells WebPack where to export the bundles it creates and how to name these files, with the default being./dist. Basically, the entire application structure is compiled into a folder in the output path you specify. You can configure these processes by specifying an output field in the configuration:

/ / webpack. Config. Js
const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'}};Copy the code

If [hash:5] is added to filename, the filename will be followed by a 5-bit hash value.

 output:{
        path:path.resolve(__dirname, 'dist'),
        filename: '[name][hash:5].bundle.js'
    },Copy the code

The configuration file

In addition to passing in parameters on the command line, Webpack can be executed using a specified configuration file. By default, the webpack.config.js file in the current directory is searched, which is a Node.js module that returns a configuration information object in JSON format, or specifies the configuration file with the –config option.

loader

Handle non-javascript files such as.less files,.css files, etc. In essence, WebPack Loader converts all types of files into modules that the application’s dependency diagram (and ultimately its bundle) can reference directly. Configure two properties: text and use.

The test property identifies the files or files that should be converted by the corresponding loader.

The use attribute indicates which loader should be used for conversion.

//webpack.config.js

const path = require('path');

const config = {
  output: {
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [{test: /\.less$/.use:'style-loader'.'css-loader'.'less-loader' }
      // Parse less files into less, convert them into CSS files, and convert them into embedded styles
      // In use, the order of parsing is reversed.]}};module.exports = config;Copy the code

Style-loader inserts the CSS code packed by THE CSS -loader into an HTML file as a

Plugins plugins

Plug-ins can do more than loaders can.

Plug-ins range from packaging optimization and compression to redefining variables in the environment. Plug-in interfaces are extremely powerful and can be used to handle a wide variety of tasks.

To use a plugin, you simply require() it and add it to the plugins array.

Most plug-ins can be customized with options.

You can also use the same plug-in multiple times for different purposes in a configuration file by using the new operator to create an instance of it.

//webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); // Install via NPM
const webpack = require('webpack'); // Used to access built-in plug-ins

const config = {
  module: {
    rules: [{test: /\.less$/.use: 'style-loader'.'css-loader'.'less-loader'}},plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'}})];module.exports = config;Copy the code

Install the NPM command in the project folder before using each plug-in.

/ / tree - shaking plug-inUglifyjs-webpack-plugin compresses JS code lodash-es/ / reference https://www.lodashjs.com/Html-webpack-plugin Put the required JS files in dist/index.html webpack-deep-scope-plugin// deep JS tree-shaking install NPM I webpack-deep-scope-plugin
/ / reference https://www.npmjs.com/package/webpack-deep-scope-pluginPurifycss-webpack Purify - CSS removes excess styles from CSS by regular matching// Go to the NPM website to search for the plugin name and see how to use it


// CSS tree-shaking NPM dependencies to installPostcss PostCSS is a tool for converting CSS with JavaScript postCSS-loader backward compatible CSS loader Autoprefixer compatible CSS properties add prefix cssnano compressed CSS files Postcss-cssnext Added cssNext syntax supportCopy the code

/ / HTML plugin

//1.html-webpack-plugin // index.html will be repackaged in dist
var HtmlWebpackPlugin = require("html-webpack-plugin");

new HtmlWebpackPlugin({
            filename: "index.html".// The name generated by the plug-in
            template: './index.html'.// Generate the template page from the original index.html
            minify: {/ / compression
                removeComments:true.// Clean up comments
                collapseWhitespace:true.// Clear the space}}),//2. Clean -webpack-plugin // Clean Spaces in HTML
var CleanWebpackPlugin = require('clean-webpack-plugin');
 new CleanWebpackPlugin();// Clear the space
 
//3.html-loaderUsage: {test:'/\.html$/'.use:[
        {
            loader:'html-loader'.options: {attrs: ['img:src'}}]}Copy the code

// Image processing plugin
url-loader
file-loader
img-loader / / https://www.npmjs.com/package/img-loader according to the need to download the loader of different image format
/ / such as:
imagemin-mozjpeg
imagemin
/ / usage:
 {
    loader:'img-loader'.options: {plugins: [require('imagemin-mozjpeg') ({quality: [0.3.0.5]// Compressed image quality range 0-1}}}),]// Compress the imageCopy the code

Install NPM install webpack-dev-server-g in the project file

NPM install webpack-dev-server -d

Perform webpack – dev – server

Webpack-dev-server –open opens in the default browser

Webpack-dev-server –open –color will be highlighted after execution

/ / in webpack. Config. Js
module.exports={
    devServer: {
        contentBase: './dist'.// The directory where the page is loaded by the local server
        port:'8082'.inline:true.// Refresh in real time
        hot: true}}// It can also be in the scripts of package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."server":"webpack-dev-server --color --open"
  }
// Enter NPM run server to start the server
Copy the code

About local server configuration has a nice post post here: www.jianshu.com/p/cbc7d342f…

Hot update

Hot Module replace Is a built-in plugin for WebPack

/ / in webpack. Config. Js
new Webpack.HotModuleReplacementPlugin()
 
// Confirm that polling request js is enabled in index.js
 if(module.hot){
    module.hot.accept()
}Copy the code

Configuring environment Variables

The development environment

// Method 1:
/ / in webpak - dev. Config. Js
module.exports = {
    mode:'development'
}

/* Enter */ on the command line webpack --config webpak-dev.config.js

// Method 2:
// In package.json scripts

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."dev":"webpack --mode development --color"."server":"webpack-dev-server --color --open"

  }
/* Enter */ on the command line npm run devCopy the code

The production environment

Module. exports = {module. Exports = {module. Exports = {module. Exports = {module.'production'} /* On the command line, type */ webpack --config webpak-prod.config.js // Method two: // in the scripts of package.json"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."prod":"webpack --mode production --color"."server":"webpack-dev-server --color --open"} /* Command line */ NPM run prodCopy the code

Determine the development or production environment by seeing if the main/index.js code under Dist is compressed

package.json

Create a project, create a new folder, create a SRC directory, create index.js, and enter NPM init -y in the root directory Git bush here to initialize NPM. -y means yes.

Projects and files are controlled through NPM, where NPM run dev packages development releases and NPM run Prod packages production releases.

//package.json
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."run": "webpack"."dev": "webpack --mode development"."prod": "webpack --mode production "
  },Copy the code

Toolkits installed via the NPM command are in devDependences in package.json files

//package.json
"devDependencies": {
    "css-loader": "^ 2.1.1"."lodash-es": "^ 4.17.11"."style-loader": "^ 0.23.1"."webpack-deep-scope-plugin": "^ 1.6.0." "
}Copy the code

We clone the project from Github and install it in the same directory as the devDependencies property in package.json.

package-lock.json

The summary is as simple as locking the version number of the package installed and uploading it to Git to ensure that everyone else has consistent dependencies when installing NPM.

According to the official documentation, package-lock.json is a file generated during NPM install to record the specific source and version of each NPM package actually installed in the current state.

What does it do? Because NPM is a manager for managing dependencies between packages, it allows developers to flag their project’s dependencies on NPM library packages in the middle of pacakge.json. You may choose to indicate the version of the library package you want

Here’s an example:

“Dependencies “: {“@types/node”: “^8.0.33”,}

The types/node library package is allowed to be downloaded if the types/node version is greater than 8.0.33 and is the same as the larger version (8). For example, you might actually download version 8.0.35 when you run NPM Install.

In most cases, there is no problem downloading the latest library package from the new compatible dependency. However, because NPM is open source, the semantics of each library package may be different, and some library developers do not adhere to the strict principle that the interface of the same library package with the same large version is compatible. At this point, the user is in trouble: in the same NodeJS code base, at different times or under different NPM download sources, the dependency package versions may be different, so the behavior of the dependency package may be different and sometimes completely incompatible.

Therefore, the latest version of NPM has started to provide automatic package-lock.json generation to let developers know that once you save the source file to a new machine or a new download source, you can download the dependent library packages according to the specific version indicated by the package-lock.json. This ensures that all library packages are exactly the same as the last one you installed.

Package – lock. Json | official documentation

Semver semantic version number changed

^ is the NPM default version symbol. When you use NPM install –save, NPM automatically adds ^ plus the version number to the package. For example: NPM install –save Angular adds “Angular “: “^1.3.15” to package.json. This symbol tells NPM to install 1.3.15 or a later version, but under major 1.

~ is also used for version control of NPM. For example, ~1.3.15 means that NPM can install 1.3.15 or later. The difference with ^ is that ~ versions can only start with 1.3. They have different scopes. You can set ~ as the default symbol by using NPM config set save-prefix=’~’.

The > symbol is mainly used to indicate that beta versions can be installed.

Semver version number | official documentation

Webpack study recommend (a good) : www.cnblogs.com/dashnowords… Webpack Resource Summary (Tencent Web front-end team) : github.com/webpack-chi…