Webpack basic configuration tutorial

1. The first Webpack

  • What is Webpack?
    • Webpack is a module packer.
    • All front-end resource files (JS /json/ CSS /img/less/…) will be added to Webpack. Are treated as modules.
    • It will analyze the dependencies of modules and generate corresponding resources
  • Five core concepts:
    1. Entry: Indicates which module WebPack should use as a starting point for building its internal dependency diagram.
    2. Output: Where to output files and how to name them.
    3. [Loader] : Handles non-javascript files (Webpack itself can only parse JavaScript and JSON).
    4. Plugins perform a wider range of tasks, from packaging to optimization.
    5. [Mode], including production mode and development mode
  • Understanding of Loader
    • Webpack itself can only handle JS and JSON modules. If you want to load other types of files (modules), you need to use the corresponding Loader.
    • It is itself a function that takes the source file as an argument and returns the result of the transformation.
    • Loader is usually named in the format of XXx-loader. XXX indicates the conversion function of the loader, such as CSS-loader.
  • Understanding plugins
    • Plug-ins can do some things that the Loader can’t.
  • The configuration file
    • Webpack.config. js: Used to store webpack configuration information.

2. Start the project

  • Initialization project:
    • usenpm initoryarn initGenerate a package.json file
      {"name": "webpack_test", "version": "1.0.0"}Copy the code
  • Install webpack
    • NPM install webpack@4 webpack-cli@3 -g // Global installation, used as a command
    • NPM install webpack@4 webpack-cli@3 -d // Used as a local dependency

3. Process JS and JSON files

  • Creating a JS file

    • src/js/app.js
    • src/js/module1.js
    • src/js/module2.js
  • Creating a JSON file

    • src/json/data.json
  • Create a home page:

    • src/index.html
  • Operation instruction

    • Package Instruction (development) :

      webpack ./src/js/app.js -o ./build/js/app.js --mode=development
      Copy the code
      • What it does: WebPack packs JS and JSON files, and converts es6’s modular syntax into a syntax that browsers can recognize
    • Package instruction (production) :

      webpack ./src/js/app.js -o ./build/js/app.js --mode=production
      Copy the code
      • Function: add a compression code function to the development configuration function
    • Add build/js/app.js to the index.html page

  • Conclusion:

    • Webpack compiles packaged JS and JSON files
    • The ability to translate es6’s modular syntax into a syntax that the browser can recognize
    • Compressible code
  • Disadvantages:

    • Files such as CSS and IMG cannot be compiled and packaged
    • Js basic ES6 syntax cannot be converted to es5 syntax
  • Improvements: Use webPack configuration file solution, custom features

4. Webpack configuration file

  • Objective: To restore the above functions by defining a configuration file in the root directory of the project
  • File name: webpack.config.js
  • Contents of the document:
const { resolve } = require('path'); // Node has a built-in core module for setting paths.

module.exports = {
    entry: './src/js/app.js'.// Import file configuration (abbreviated)
    /* Entry :{main:'./ SRC /js/app.js'} */
    output: { // Output configuration
        filename: './js/app.js'.// Output the file name
        path: resolve(__dirname, 'build')// Output file path (absolute path)
    },
    mode: 'development'   // Development environment (choose one of two)
    //mode: 'production'
};
Copy the code
  • Run instruction: webpack

5. Pack less and CSS resources

  • Overview: Less and CSS files cannot be parsed by Webpack and need to be compiled and parsed by Loader

  • Creating less files

    • src/css/demo1.less
    • src/css/demo2.css
  • Entry app.js file

    • Import less and CSS resources
  • Install the loader

    • npm install css-loader style-loader less-loader less -D
  • Configure the loader

    {
    	// Process less resources
    	test: /\.less$/,
    	use: [
    		'style-loader'.// Create a style tag and insert the js style resource into the head
    		'css-loader'.// Change the CSS file into a commonJS module and load the js file with the style string
    		'less-loader' // Compile less files into CSS files] {},// Process CSS resources
    	test: /\.css$/,
    	use: [ // The sequence of loader execution in the use array is from right to left and from bottom to top
    		'style-loader'.// Create a style tag and insert the js style resource into the head
    		'css-loader'// Change the CSS file into a commonJS module and load the js file with the style string]},Copy the code
  • Run instruction: webpack

6. Package HTML files

  • Summary: Package HTML resources with the HTML-webpack-plugin

  • Creating an HTML file

    • src/index.html
    • Note: Do not introduce any CSS and JS files into this HTML
  • Install the plugin: html-webpack-plugin

    • npm install html-webpack-plugin -D
  • Import plug-ins in webpack.config.js (plug-ins need to be imported manually and loader automatically loads them)

    • const HtmlWebpackPlugin = require(‘html-webpack-plugin’)
  • Configure plug-in Plugins

    plugins: [
      new HtmlWebpackPlugin({
    	// Create a new HtML using the current file as a template (1. Packaged resources are automatically introduced)
        template: './src/index.html',}),]Copy the code
  • Run instruction: webpack

7. Wrap images in styles

  • Summary: Image file webpack cannot parse, need to use loader to compile parse
  • Add 2 images:
    • Small image, less than 8KB: SRC /images/vue.png
    • Large image, larger than 8KB: SRC /images/react.jpg
  • Introduce two images in the less file by way of a background image
  • Install the loader
    • npm install file-loader url-loader file-loader -D
    • Add: Url-loader is the upper-layer encapsulation of file-loader, and it must be used together with file-loader.
  • Configure the loader
    {
    	// Process image resources
    	test: /\.(jpg|png|gif)$/,
    	loader: 'url-loader'.//url-loader is an upper-level encapsulation of file-loader
    	options: {
    		limit: 8 * 1024.// The threshold is 8KB. Images smaller than 8KB will be base64 encoded
    		name: '[hash:10].[ext]'.// The name of the processed image
    		outputPath: 'imgs' // Output path}},Copy the code

8. Wrap images in HTML

  • Summary: the tag in HTML cannot be processed by the URl-loader and needs to be processed by another loader.

  • Add images

    • Add an img tag to SRC /index.html, SRC /images/angular.png
  • Install the loader

    • npm install html-loader –save-dev
  • Configure the loader

    {
    	// Process  resources in HTML
    	test: /\.html$/,
    	loader: 'html-loader'
    },
    Copy the code
  • Possible pitfall: The SRC of the image in the packaged HTML file is changed to: [Object Module],

  • Solution: Add esModule:false to url-loader

Pack other resources

  • Summary: Other resources (fonts, audio and video, etc.) cannot be parsed by Webpack and need to be compiled and parsed by Loader
  • For a font with several font ICONS, add several downloaded font files under font:
    • src/font/iconfont.eot
    • src/font/iconfont.svg
    • src/font/iconfont.ttf
    • src/font/iconfont.woff
    • src/font/iconfont.woff2
  • Modify the URL of the font in incofont. CSS
    @font-face {
      font-family: 'iconfont';
      src: url('.. /media/iconfont.eot');
      src: url('.. /media/iconfont.eot? #iefix') format('embedded-opentype'),
      url('.. /media/iconfont.woff2') format('woff2'),
      url('.. /media/iconfont.woff') format('woff'),
      url('.. /media/iconfont.ttf') format('truetype'),
      url('.. /media/iconfont.svg#iconfont') format('svg');
    }
    
    .iconfont {
      font-family: "iconfont" ! important;
      font-size: 16px;
      font-style: normal;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
    Copy the code
  • Modify HTML to add font ICONS, for example:<span class="iconfont icon-icon-test"></span>
  • Configure the loader
    {
    	// Handle other resources (fonts, audio and video, etc.)
    	exclude: /\.(html|js|css|less|jpg|png|gif)/.// Exclude files
    	loader: 'file-loader'.options: {
    		name: '[hash:10].[ext]'./ / name
    		outputPath: 'media' // Output path}}Copy the code
  • Run instruction: webpack

10. devServer

  • Webpack – dev – server installation

    • npm i webpack-dev-server -D
    • npm i webpack-dev-server -g
    • For details, see the official website: Guide -> Development Environment -> Using Webpack-dev-server
  • Modify webPack configuration object, append devServer configuration (note not append in loader)

    //devServer configuration (development mode specific configuration)
    devServer: {
    	contentBase: resolve(__dirname, 'build'),// The location of the local package file
    	port: 3000./ / the port number
    	open: true // Automatically open the browser
    }
    Copy the code
  • Modify the scripts directive in package.json

    • "dev": "webpack-dev-server".
  • Run command: NPM run dev or YARN dev


At this point, you have built a simple development environment with WebPack, but this configuration is only suitable for debugging code during development. It will not apply when the project goes live, because you still have a lot of problems to deal with, such as: CSS is not a separate file, CSS, JS there are many compatibility issues and so on, next we start to build the production environment.

Preparation for production environment:

1. Create a config folder, rename webpack.config.js to webpack.dev.js, and put it in config folder 2. Copy webpack.dev.js, rename it webpack.prod.js, and remove the devServer configuration from it, as this is specific to the development environment and not needed in production 3. Modify the scripts directive in package.json:

"start": "webpack-dev-server --config ./config/webpack.dev.js"."build": "webpack --config ./config/webpack.prod.js"
Copy the code

Path: resolve(__dirname, ‘.. /build’)

1. Extract the CSS as a separate file

  • Installing a plug-in

    • npm install mini-css-extract-plugin -D
  • The introduction of the plugin

    • const MiniCssExtractPlugin = require(“mini-css-extract-plugin”);
  • Configure the loader

    // Introduce the mini-css-extract-plugin for extracting CSS as a separate file
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    {
      // Process less resources
      test: /\.less$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader'.'less-loader',]}, {// Process CSS resources
      test: /\.css$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader']},Copy the code
  • Configure the plug-in

    // Extract CSS as a separate file
      new MiniCssExtractPlugin({
      	// Rename the output CSS file
      	filename: 'css/built.css',})Copy the code
  • Operation instruction

    • npm run build
  • The solution is to add: publicPath:’/’ publicPath to output configuration. If the value of online running is: /imgs, if the value of local right-click running is: /imgs /build/imgs

2. Check the CSS compatibility

  • Install the loader
    • npm install postcss postcss-loader postcss-preset-env -D
  • Since CSS and LESS style files are compatible, we define a common configuration:
// Configure a commonCssLoader to handle less and CSS
const commonCssLoader = [
	MiniCssExtractPlugin.loader, // Extract CSS as a separate file
	'css-loader'.// Change the CSS file into a commonJS module and load the js file with the style string
	{
		 // Note: For postCSS-loader to work, you also need to define browserslist configuration compatibility in package.json
		 loader: 'postcss-loader'.options: {
          ident: 'postcss'.plugins: () = > [require('postcss-preset-env') (the)]}}];Copy the code
  • Modify the configurations of CSS-Loader and less-loader
	{
		// Process CSS resources
		test: /\.css$/,
		use: [...commonCssLoader]
	},
	{
		// Process less resources
		test: /\.less$/,
		use: [...commonCssLoader, 'less-loader']},Copy the code
  • Configure package.json to append the Browserslist configuration to load the specified CSS compatibility style through the configuration

    "browserslist": {
    	// Development environment
    	"development": [
    		"last 1 chrome version"."last 1 firefox version"."last 1 safari version"].// Production environment: Production environment by default
    	"production": [
    		"0.2%" >.// Compatible with 99.8% of browsers on the market
    		"not dead".//" dead "browsers are not compatible, such as IE8
    		"not op_mini all".// Do not make opera mini compatible
    		"ie 10" / / build is compatible]}Copy the code
  • Note 1: Browserslist is a set of tools that describe the target operating environment of a product. Browserslist is widely used in various compatibility support tools involving browsers and mobile devices. For detailed configuration rules, see github.com/browserslis…

  • Note 2: If the version is incompatible or the configuration is incorrect, change the dependent package version.

    npm i less-loader@5 postcss-loader@3
    Copy the code
  • Operation instruction:

    • npm run build

3. Js syntax check

  • Overview: Check in advance for js basic syntax errors/hidden dangers

  • Install the loader

    • npm install eslint-loader eslint -D
  • Install check rule library:

    • npm install eslint-config-airbnb-base eslint-plugin-import -D
  • Note: ESlint-config-Airbnb-base provides a set of standard and common JS syntax checking rules, which are recommended

  • Configure the loader

    module: {
      rules: [{// Check the syntax of js
            test: /\.js$/,
            exclude: /node_modules/.// Exclude this file
            // Priority execution
            enforce: 'pre'.// preferentially execute as long as webPack starts as early as possible without writing
            loader: 'eslint-loader'.options: {
              fix: true // If there is a problem automatic repair, important !!!!}}}]Copy the code
  • Modify the underlying implementation of the package.json library

    "eslintConfig": {
      "extends": "airbnb-base".// Use the rules provided by Airbnb-base directly
      "env": {
       "browser": true// If the runtime environment is node and not a browser, change this to false}}Copy the code
  • Run instruction: webpack

  • Note: If you find: Warning Unexpected Console statement no-console warning, you should not write console.log() in your project. To ignore this, enter a comment above the code you want to ignore. // eslint-disable-next-line will work.

    The yellow warning indicates that the log was printed and you can either add eslint-disable-next-line to it or leave it alone

4. Js syntax conversion

  • Overview: Convert the new syntax that is not recognized by the browser to the old syntax that is recognized by the browser

  • Install the loader

    • Webpack4 or later can be installed directly. Webpack3 also needs to be defined @ Refer to the official website for the later version
    • npm install babel-loader @babel/core @babel/preset-env -D
  • Configure the loader

    module: {
      rules: [{test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader".options: {
              presets: ['@babel/preset-env'}}}]}Copy the code
  • Run instruction: webpack

5. Js compatibility processing

  • The installation package

    • npm install @babel/polyfill

      Lin-used for advanced compatibility can solve large projects that cannot be solved in Babel. No need to remember can solve the problem of not recognizing promises in IE

      Introduced in app.js

  • use

    - app.js import '@babel/polyfill'; // Contains ES6 advanced syntax conversionsCopy the code

6. Compress HTML and JS

  • Change the model in webpack.prod.js to production.
  • Note: If mode is set to Production, configuration minify: false: must be added to new HtmlWebpackPlugin.
new HtmlWebpackPlugin({
    // Create a new HtML using the current file as a template (1. Packaged resources are automatically introduced)
    template: './src/index.html'.minify: false
}),
Copy the code

7. Compress CSS

Optimize assets with WEBPack 4.0 and above

  • Installing a plug-in

    npm install optimize-css-assets-webpack-plugin -D 
    Copy the code
  • The introduction of the plugin

    const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');	
    Copy the code
  • Configure the plug-in

    new OptimizeCssAssetsPlugin({
      cssProcessorPluginOptions: {
        preset: ['default', { discardComments: { removeAll: true}}].// Remove all comments}})Copy the code

    This is the configuration of the WebPack production environment to generate packaged files.

conclusion

1. Webpack configuration file

Module. exports = {entry: '', // exports output: {},// exports module: {// config loader rules: []}, plugins: [], // Plugin model: working mode}Copy the code

2. Basic process of Webpack packaging

  • Connect: Webpack starts with entry JS, recursively finds all related modules, and connects them together to form a graph (net) structure
  • Compile: Converts the modular syntax of a JS module into a module syntax that the browser can run directly (although other types of resources also handle this)
  • Merge: Combine all the compiled modules in the diagram into one or a few files. The browser really runs as a packaged file

3. Compare Loaders with plugins

  • Loader: Used to load specific types of resource files. Webpack itself can only pack JS and JSON.
  • Plugin: used to extend the functions of other aspects of Webpack. The resources and operations that cannot be handled by the general loader are handed over to the plug-in.

4. Live-reload vs. HMR

  • Similarities: Code changes are automatically recompiled and packaged
  • Live-reload: refresh the whole page to see the effect of the latest code, and the page state is all new. HMR: instead of refreshing the entire page, just load the package file of the modification module and run it, so as to update the partial interface of the page, and the state of the rest of the interface is still there

5. Summary of common Loader and Plugin in Webpack

Commonly used loader:

2. Cs-loader is used to pack CSS into JS with CommonJs syntax. 3. Style-loader is used to dynamically create a style label. 4. File-loader is used to process other resources, as well as image resources. The core operations are extracting resources to specified locations and modifying file names. 5. [URL-loader] is almost the same as the file-loader function, with the advantage that it can dynamically transform the image base64 encoding (control limit attribute value can control the threshold). Note: Url-loader is more widely used than file-loader, and url-loader is the upper-layer encapsulation of file-loader. 6. Html-loader is used to process images with < IMG > tags in HTML. 6. [esint-loader] Checks the JS syntax in the project. 7. [babel-loader] convert ES6 syntax to ES5 syntax Note 1: If used directly, only simple syntax can be processed, and Promise cannot be processed. Note 2: Use Polyfill to complete the conversion of advanced ES6 syntax. Disadvantages: All conversions cannot be performed on demand, resulting in large JS volume. Note 3: Use Core-JS and Polyfill to complete conversion on demand. 8. [postCSS-loader] LoadR, used to deal with CSS compatibility problems, needs to be used with [PostCSS] and [PostCSS-PRESET -env] note 1: Time used is: [" CSS - loader ", "postcss - loader", "less - loader"]. Note 2: You need to configure the Browserslist property in package.json to specify specific compatibility rules. Note 3: Browserslist is a separate library that is widely used in a variety of browser/mobile compatibility support toolsCopy the code

Commonly used pulgins:

1. [mini-CSS-extract-plugin] : Used to extract CSS from the project into a separate file. Note 1: the use of time is: [MiniCssExtractPlugin loader, "CSS - loader", "postcss - loader", less - loader]." Note 2: Plugins can be passed in to new for example: {loader: "postCSs-loader ", options: {postcssOptions: {plugins: [" postCSs-env "]}}} 2.【html-webpack-plugin] : Automatic creation of HTML files and automatic introduction of external resources 3.【eslint-plugin-import】 : 4. Eslint-config-airbnb-base is used to introduce the syntax check rule configured by Airbnb, otherwise it needs to be configured one by one, which is quite cumbersome. 5. 6. [optimize- CSS -assets-webpack-plugin] is used to compress CSSCopy the code

6. Tree-shaking in webpack

  1. Overview: Sometimes we have n functions, objects, or other data exposed in a module, but we only use one or a few of them. When it comes to final packaging, we only want to package what we use. Tree-shaking, that is, removing useless code.

  2. Configuration: Webpack automatically turns on tree-shaking if both conditions are met

1. Use ES6 modularization. 2Copy the code