Previous study notes, in this collation, easy to view the code base

1. Webpack profile

1. Five core concepts of Webpack

  • The Entry Entry indicates which file webPack starts packing as a starting point, analyzing and building internal dependency diagrams.

  • Output Output indicates where the resource bundle Output of webPack packaging goes and how to name it.

  • Loader allows WebPack to handle non-javascript files (Wenpack itself can only understand JavaScript) – acting as translator

  • Plugins can be used to perform a much wider range of tasks. Plug-ins range from packaging optimization and compression to redefining variables in the environment.

  • The Mode Mode (Mode) instructs WebPack to use the appropriate configuration

    options describe The characteristics of
    development Process.env.node_env is set to development and NamedChunksPlugin and NamedModulesPlugins are enabled An environment that allows code to be debugged and run locally
    production Process.env.node_env is set to production, To enable the FlagDependencyUsagePlugin, FlagIncludedChunksPlugin, ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and UglifyJsPlugin An environment that optimizes code to run online

2. Webpack early experience

2.1 Installing webPack WebPack using the CLI

2.2 packaging

// Build /built. Js --mode=development // Webpack will start packing with./ SRC /index.js as entry file. /build/built. Js: webpack. / SRC /index.js -o./build/built. Js --mode=productionCopy the code
*** Conclusion: 1. Webpack can handle JAVASCRIPT, JSON resources, CSS, IMG and other resources directly. Production and development environments modularize ES6 into modules that browsers recognize 3. The production environment has one more zip code than the development environmentCopy the code

3. Pack the style file

3.1 webpack configuration

/* Webpack.config. js Webpack's config file is used to tell webpack what to do. All the components of the tool run on the NodeJS platform, modularity default commonJS */

const { resolve } = require('path');
module.exports = {
  / / the entry
  entry: './src/index.js'./ / output
  output: {
    // Output the file name
    filename: 'built.js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// Loader configuration
  // Different files need to be processed by different Loader
  module: {
    rules: [
      // Loader configuration details
      {
        // Match those files
        test: /\.css$/.// Use those loader processes
        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Create a style tag and insert the js style resource into the head
          'style-loader'.// Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'] {},// Match those files
        test: /\.less$/.// Use those loader processes
        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Create a style tag and insert the js style resource into the head
          'style-loader'.// Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'.// Compile less files into CSS files
          // Less and less-loader need to be downloaded
          'less-loader']]}},plugins: [
    // Detailed plugin configuration].mode: 'development' /* Development mode */
  // mode:'production' /* Production mode */
};
Copy the code

4. Packaging HTML

The main requirement is the HTML-webpack-plugin

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  / / the entry
  entry: './src/index.js'./ / output
  output: {
    // Output the file name
    filename: 'built.js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// Loader configuration
  // Different files need to be processed by different Loader
  module: {
    rules: [
      // Loader configuration details
      {
        // Match those files
        test: /\.css$/.// Use those loader processes
        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Create a style tag and insert the js style resource into the head
          'style-loader'.// Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'] {},// Match those files
        test: /\.less$/.// Use those loader processes
        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Create a style tag and insert the js style resource into the head
          'style-loader'.// Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'.// Compile less files into CSS files
          // Less and less-loader need to be downloaded
          'less-loader']]}},plugins: [
    // Detailed plugin configuration
    // html-webpack-plugin
    // Function: Creates an empty HTML file by default. Automatically import all resources that are packaged for output
    new HtmlWebpackPlugin({
      // Copy the template file and automatically import all of the resources packaged for output
      template: './src/index.html'})].mode: 'development' /* Development mode */
  // mode:'production' /* Production mode */
};
Copy the code

5. Pack your photo resources

  • Image resources are packaged into IMG tags in HTML and background images in style files, which need to be processed by different loaders.
/* Webpack.config. js Webpack's config file is used to tell webpack what to do. All the components of the tool run on the NodeJS platform, modularity default commonJS */

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  / / the entry
  entry: './src/index.js'./ / output
  output: {
    // Output the file name
    filename: 'built.js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// Loader configuration
  // Different files need to be processed by different Loader
  module: {
    rules: [
      // Loader configuration details
      {
        // Match those files
        test: /\.css$/.// Use those loader processes
        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Create a style tag and insert the js style resource into the head
          'style-loader'.// Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'] {},// Match those files
        test: /\.less$/.// Use those loader processes
        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Create a style tag and insert the js style resource into the head
          'style-loader'.// Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'.// Compile less files into CSS files
          // Less and less-loader need to be downloaded
          'less-loader'] {},// Match image files
        // Can't process images in HTML by default
        test: /\.(jpg|png|gif)$/.// To use those loader processes, you need to download two packages url-loader file-loader
        Use: []
        loader: 'url-loader'.options: {
          // If the image is less than 20Kb, base64 will be used
          // Advantages: reduced number of requests (reduces server stress)
          // Disadvantages: Larger image size (slower file request)
          limit: 20 * 1024.
          // Solution: Disable THE ES6 modularity of urL-loader and use commonJS
          esModule: false.// [hash:10] Specifies the first ten digits of the hash. [ext] specifies the file extension
          name: '[hash:10].[ext]'}}, {// Match image files
        // url-loader cannot process images in HTML by default
        test: /\.(html)$/.Use: []
        loader: 'html-loader'}},plugins: [
    // Detailed plugin configuration
    // html-webpack-plugin
    // Function: Creates an empty HTML file by default. Automatically import all resources that are packaged for output
    new HtmlWebpackPlugin({
      // Copy the template file and automatically import all of the resources packaged for output
      template: './src/index.html'})].mode: 'development' /* Development mode */
  // mode:'production' /* Production mode */
};
Copy the code

Pack other resources

  • Other resources are packaged using file-loader
  {
        // Match other files. Matching resources can either use test or exclude to exclude certain files. Both can exist at the same time
        test: /\.(ttf|mp4|json)$/,
        exclude: /\.(css|js|html|png|jpg|gif|less)$/.Use: []
        loader: 'file-loader'.// [hash:10] Specifies the first ten digits of the hash. [ext] specifies the file extension
        options: {
          name: '[hash:10].[ext]'}}Copy the code

7. devServer

  // DevServer: for automation (automatically compile, automatically open browser, automatically refresh browser)
  // Features: only packages are compiled in memory, with no output
  NPX webpack-dev-server: NPX webpack-dev-server: NPX webpack-dev-server
  devServer: {
    contentBase: resolve(__dirname, 'build'),
    // Start gzip compression
    compress: true./ / the port number
    port: 3000.// Automatically open the browser
    open:true
  }
Copy the code

2. Optimized production environment configuration

8. Extract the CSS file into a single file

  • The mini-CSS-extract-plugin is required
  • There are two main modifications:
    1. Introduce and use plug-ins
    2. Instead of style-loader, less and CSS need to be handled
/* Webpack.config. js webpack configuration file: instructs webpack to do what work all the component tools are based on nodeJS platform, modularity default commonJS */

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const miniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  / / the entry
  entry: './src/js/index.js'./ / output
  output: {
    // Output the file name
    filename: 'js/built.js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// Loader configuration
  // Different files need to be processed by different Loader
  module: {
    rules: [
      // Loader configuration details
      {
        // Match those files
        test: /\.css$/.// Use those loader processes
        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Create a style tag and insert the js style resource into the head
          // 'style-loader',
          / / use miniCssExtractPlugin. Loader instead of style - loader, will separate CSS file
          miniCssExtractPlugin.loader,
          // Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'] {},// Match those files
        test: /\.less$/.// Use those loader processes
        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Create a style tag and insert the js style resource into the head
          // 'style-loader',
          / / use miniCssExtractPlugin. Loader instead of style - loader, will separate CSS file
          miniCssExtractPlugin.loader,
          // Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'.// Compile less files into CSS files
          // Less and less-loader need to be downloaded
          'less-loader']]}},plugins: [
    // Detailed plugin configuration
    // html-webpack-plugin
    // Function: Creates an empty HTML file by default. Automatically import all resources that are packaged for output
    new HtmlWebpackPlugin({
      // Copy the template file and automatically import all of the resources packaged for output
      template: './src/index.html'
    }),
    // Run the following command to extract the CSS as a single file
    new miniCssExtractPlugin({
      // The output file name and path
      filename: 'css/bulid.css'})].mode: 'development' /* Development mode */.// mode:'production' /* Production mode */
  // DevServer: for automation (automatically compile, automatically open browser, automatically refresh browser)
  // Features: only packages are compiled in memory, with no output
  NPX webpack-dev-server: NPX webpack-dev-server: NPX webpack-dev-server
  devServer: {
    contentBase: resolve(__dirname, 'build'),
    // Start gzip compression
    compress: true./ / the port number
    port: 3000.// Automatically open the browser
    open: true}};Copy the code

9. Check the compatibility of CSS files

  • Install postCSs-env and postCSs-loader to help PostCSS find the configuration in package.json browserList. Load specified CSS-compatible styles through configuration, default to production configuration
/* Webpack.config. js webpack configuration file: instructs webpack to do what work all the component tools are based on nodeJS platform, modularity default commonJS */

// Set the node environment variable to run
process.env.NODE_ENV='development'

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const miniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  / / the entry
  entry: './src/js/index.js'./ / output
  output: {
    // Output the file name
    filename: 'js/built.js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// Loader configuration
  // Different files need to be processed by different Loader
  module: {
    rules: [
      // Loader configuration details
      {
        // Match those files
        test: /\.css$/.// Use those loader processes

        use: [
          // Order of execution in the use array: right to left, bottom to top
          // Separate the CSS file
          miniCssExtractPlugin.loader,
          // Load the CSS file as a commonJS module in js. The content inside is the style string
          'css-loader'.// CSS compatibility processing, postCSS is required. Install postCSs-env and postCSS-loader
          // Help postcss to find the configuration in package.json browserList. Load the specified CSS-compatible styles through the configuration
          /* "browseslist":{ "development":[ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ], "Production" : [" > 0.2% ", "not dead", "not op_mini all"]} * /
          /* Use the default loader configuration format: 'postCSs-loader' */
          // Modify the loader configuration in the following format
          {
            loader: 'postcss-loader'.options: {
              ident: 'postcss'.plugins: () = > [
                 // PostCSs-preset -env plugin, has some preset compatibility processing
                require('postcss-preset-env') (); ] }}]}, {// Match image files
        // Can't process images in HTML by default
        test: /\.(jpg|png|gif)$/.// To use those loader processes, you need to download two packages url-loader file-loader
        Use: []
        loader: 'url-loader'.options: {
          // If the image is less than 20Kb, base64 will be used
          // Advantages: reduced number of requests (reduces server stress)
          // Disadvantages: Larger image size (slower file request)
          limit: 20 * 1024.
          // Solution: Disable THE ES6 modularity of urL-loader and use commonJS
          esModule: false.// [hash:10] Specifies the first ten digits of the hash. [ext] specifies the file extension
          name: '[hash:10].[ext]'.// Output directory build/img
          outputPath: 'img'}}, {// Match image files
        // url-loader cannot process images in HTML by default
        test: /\.(html)$/.Use: []
        loader: 'html-loader'
      },
      {
        // Match other files. Matching resources can either use test or exclude to exclude certain files. Both can exist at the same time
        test: /\.(ttf|mp4|json)$/,
        exclude: /\.(css|js|html|png|jpg|gif|less)$/.Use: []
        loader: 'file-loader'.// [hash:10] Specifies the first ten digits of the hash. [ext] specifies the file extension
        options: {
          name: '[hash:10].[ext]'}}},plugins: [
    // Detailed plugin configuration
    // html-webpack-plugin
    // Function: Creates an empty HTML file by default. Automatically import all resources that are packaged for output
    new HtmlWebpackPlugin({
      // Copy the template file and automatically import all of the resources packaged for output
      template: './src/index.html'
    }),
    // Run the following command to extract the CSS as a single file
    new miniCssExtractPlugin({
      // The output file name and path
      filename: 'css/bulid.css'})].mode: 'development' /* Development mode */.// mode:'production' /* Production mode */
  // DevServer: for automation (automatically compile, automatically open browser, automatically refresh browser)
  // Features: only packages are compiled in memory, with no output
  NPX webpack-dev-server: NPX webpack-dev-server: NPX webpack-dev-server
  devServer: {
    contentBase: resolve(__dirname, 'build'),
    // Start gzip compression
    compress: true./ / the port number
    port: 3000.// Automatically open the browser
    open: true}};Copy the code

10. Compress CSS

  • Optimize – CSS -assets-webpack-plugin is a plugin for optimize- CSS – Assets -webpack-plugin
/* Webpack.config. js webpack configuration file: instructs webpack to do what work all the component tools are based on nodeJS platform, modularity default commonJS */
// optimize CSS plugin: optimize- CSS -assets-webpack-plugin
const optimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
  plugins: [new optimizeCssAssetsWebpackPlugin()],
  mode: 'development' /* Development mode */
};
Copy the code

11. Code review

  • The esLint eslint-loader is used to check the js files, excluding third-party code
  • Example specification: Airbnb-base specification
/* Webpack.config. js webpack configuration file: instructs webpack to do what work all the component tools are based on nodeJS platform, modularity default commonJS */

// Set the node environment variable to run
process.env.NODE_ENV = 'development';

const { resolve } = require('path');

module.exports = {
  / / the entry
  entry: './src/js/index.js'./ / output
  output: {
    // Output the file name
    filename: 'js/built.js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// Loader configuration
  // Different files need to be processed by different Loader
  module: {
    rules: [{// Syntax check: eslint-loader eslint
        // Example specification: eslint-plugin-import eslint-config-airbnb-base
        // Note: only check your own code, not third-party code
        test: /\.js$/.// Exclude third-party code
        exclude: /node_modules/,
        loader: 'eslint-loader'.options: {
          // Automatic repair
          fix: true}}},plugins: [].mode: 'development'.devServer: {}};Copy the code

package.json

  "eslintConfig": {
    "extends":"airbnb-base"
  },
Copy the code

12. Js compatibility processing

/* Webpack.config. js webpack configuration file: instructs webpack to do what work all the component tools are based on nodeJS platform, modularity default commonJS */

// Set the node environment variable to run
process.env.NODE_ENV = 'development';

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const miniCssExtractPlugin = require('mini-css-extract-plugin');

// optimize CSS plugin: optimize- CSS -assets-webpack-plugin

const optimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  / / the entry
  entry: './src/js/index.js'./ / output
  output: {
    // Output the file name
    filename: 'js/built.js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// Loader configuration
  // Different files need to be processed by different Loader
  module: {
    rules: [{// PREsets are compatible with babel-loader@babel /preset- env@babel /core
        // Scenario 1, Basic JS compatible processing -- "@babel/preset-env
        // Problem: only basic syntax can be converted
        // Plan 2. All js processing (promise...) Download @babel/polyfill and just use it in the global JS import. Webpack does not need to be configured
        // Problem: all compatible processing code is introduced. Increased code volume
        // Select * from core-js; // select * from core-js;
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'.options: {
          presets: [['@babel/preset-env',
              {
                // Load as needed
                useBuiltIns: 'usage'.// Specify the version of core-js
                corejs: {
                  version: 3
                },
                // Specify which browser version is compatible with
                targets: {
                  chrome: '60'.firefox: '60'.ie: '9'}}]]}}]},plugins: [].mode: 'development' /* Development mode */.devServer: {
    contentBase: resolve(__dirname, 'build'),
    // Start gzip compression
    compress: true./ / the port number
    port: 3000.// Automatically open the browser
    open: true}};Copy the code

Compress JS and HTML

// Change mode to production environment, js files will be compressed automatically
mode: 'production';

HTML / / compression
new HtmlWebpackPlugin({
  // Copy the template file and automatically import all of the resources packaged for output
  template: './src/index.html'.HTML / / compression
  minify: {
    // Delete Spaces
    collapseWhitespace: true.// Remove comments
    removeComments: true}});Copy the code

14. Configure the production environment

/* Webpack.config.js webpack configuration files are used to tell webpack what to do. All components of the tools run on the NodeJS platform, and modularity defaults to CommonJS */

process.env.NODE_ENV = 'production';
const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const miniCssExtractPlugin = require('mini-css-extract-plugin');

// optimize CSS plugin: optimize- CSS -assets-webpack-plugin

const optimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');

const commonCssLoader = [
  // Order of execution in the use array: right to left, bottom to top
  // Separate the CSS file
  miniCssExtractPlugin.loader,
  // Load the CSS file as a commonJS module in js. The content inside is the style string
  'css-loader',
  {
    loader: 'postcss-loader'.options: {
      ident: 'postcss'.// PostCSs-preset -env plugin, has some preset compatibility processing
      plugins: () = > [require('postcss-preset-env') (the)]}}];module.exports = {
  / / the entry
  entry: './src/js/index.js'./ / output
  output: {
    // Output the file name
    filename: 'js/built.js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// Loader configuration
  // Different files need to be processed by different Loader
  module: {
    rules: [
      // Loader configuration details
      {
        // Match those files
        test: /\.css$/.// Use those loader processes
        use: [...commonCssLoader]
      },
      {
        test: /\.less$/,
        use: [...commonCssLoader, 'less-loader'] {},// Match image files
        // Can't process images in HTML by default
        test: /\.(jpg|png|gif)$/.// To use those loader processes, you need to download two packages url-loader file-loader
        Use: []
        loader: 'url-loader'.options: {
          // If the image is less than 20Kb, base64 will be used
          // Advantages: reduced number of requests (reduces server stress)
          // Disadvantages: Larger image size (slower file request)
          limit: 20 * 1024.
          // Solution: Disable THE ES6 modularity of urL-loader and use commonJS
          esModule: false.// [hash:10] Specifies the first ten digits of the hash. [ext] specifies the file extension
          name: '[hash:10].[ext]'.// Output directory build/img
          outputPath: 'imgs'}}, {// Handle image files in HTML
        // url-loader cannot process images in HTML by default
        test: /\.(html)$/.Use: []
        loader: 'html-loader'
      },
      {
        // Match other files. Matching resources can either use test or exclude to exclude certain files. Both can exist at the same time
        test: /\.(ttf|mp4|json)$/,
        exclude: /\.(css|js|html|png|jpg|gif|less)$/.Use: []
        loader: 'file-loader'.// [hash:10] Specifies the first ten digits of the hash. [ext] specifies the file extension
        options: {
          name: '[hash:10].[ext]'}}, {// Syntax check: eslint-loader eslint
        // Example specification: eslint-plugin-import eslint-config-airbnb-base
        /* package.json: "eslintConfig": { "extends": "airbnb-base" }, */
        // Note: only check your own code, not third-party code
        test: /\.js$/.// Exclude third-party code
        exclude: /node_modules/,
        loader: 'eslint-loader'.// If the same file executes different loaders, this loader will be executed first
        enforce: 'pre'.options: {
          // Automatic repair
          fix: true}}, {// PREsets are compatible with babel-loader@babel /preset- env@babel /core
        // Scenario 1, Basic JS compatible processing -- "@babel/preset-env
        // Problem: only basic syntax can be converted
        // Plan 2. All js processing (promise...) @babel/polyfill, which only needs to be used in global JS import. Webpack does not need to be configured
        // Problem: all compatible processing code is introduced. Increased code volume
        // Solution 3. Need to load on demand, need compatibility only do
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'.options: {
          presets: [['@babel/preset-env',
              {
                // Load as needed
                useBuiltIns: 'usage'.// Specify the version of core-js
                corejs: {
                  version: 3
                },
                // Specify which browser version is compatible with
                targets: {
                  chrome: '60'.firefox: '60'.ie: '9'}}]]}}]},plugins: [
    // Detailed plugin configuration
    // html-webpack-plugin
    // Function: Creates an empty HTML file by default. Automatically import all resources that are packaged for output
    new HtmlWebpackPlugin({
      // Copy the template file and automatically import all of the resources packaged for output
      template: './src/index.html'.minify: {
        // Delete Spaces
        collapseWhitespace: true.// Remove comments
        removeComments: true}}),// Run the following command to extract the CSS as a single file
    new miniCssExtractPlugin({
      // The output file name and path
      filename: 'css/bulid.css'
    }),
    new optimizeCssAssetsWebpackPlugin()
  ],
  // mode: 'development' /* Development */,
  mode: 'production' /* Production mode */.// DevServer: for automation (automatically compile, automatically open browser, automatically refresh browser)
  // Features: only packages are compiled in memory, with no output
  NPX webpack-dev-server: NPX webpack-dev-server: NPX webpack-dev-server
  devServer: {
    contentBase: resolve(__dirname, 'build'),
    // Start gzip compression
    compress: true./ / the port number
    port: 3000.// Automatically open the browser
    open: true}};Copy the code

3. Performance optimization

15. Development Environment –HMR

  • All you need to do is set devServer to hot: true
/ * HMR: module to replace | hot update: a module change, will only to repackage the module, so as to speed up the packing problem: the style file: can use HMR, because the style - loader internal implementation; Js files: HMR cannot be used by default, HMR support code needs to be added, note: only non-entry files can be processed. HTML files: HMR cannot be used by default. HTML: change the entry entry to an array, and import the HTML file into js: If (module.hot){module.hot.accept('./ SRC /xxx.js',function(){// the method will listen for changes in the xxx.js file. If changes are made, other files are not repackaged by default. Such as calling a function})} */

  devServer: {
    contentBase: resolve(__dirname, 'build'),
    // Start gzip compression
    compress: true./ / the port number
    port: 3000.// Automatically open the browser
    open: true./ / open the HMR
    hot: true
  }
Copy the code

16.source-map

/* source-map: a technique to map the source code to the built code (if the built code fails, the map can trace the source code error) [the inline - | hidden - | eval -] [nosources -] [being - [module -]] source - the map source - the map: External [Exact information on error code and error location of source code] inline-source-map: The map file is inside the original JS file. No external file is generated. Build faster [exact information about error code and error location of source code] hidden-source-map [Exact information about error code and error location of source code cannot be traced] eval-source-map: Nosource-map: external nosource-map: external nosource-map: external nosource-map: external nosource-map: external Fast and debug-friendly (eval>inline> Cheap >...) Debug friendly: source-map cheap-module-source-map cheap-source-map Production environment: Should source code be hidden? Debug friendly questions? Inlining makes the code bigger, so production environments don't use nosource-source-map to hide all hidden-source-map only hides the source code, which will show errors */ after the code is built
Copy the code

17.oneOf

  • OneOf, improve packaging speed, optimize matching loader rules
  module: {
    rules: [{// Syntax check: eslint-loader eslint
        // Example specification: eslint-plugin-import eslint-config-airbnb-base
        /* package.json: "eslintConfig": { "extends": "airbnb-base" }, */
        // Note: only check your own code, not third-party code
        test: /\.js$/.// Exclude third-party code
        exclude: /node_modules/,
        loader: 'eslint-loader'.// If the same file executes different loaders, this loader will be executed first
        enforce: 'pre'.options: {
          // Automatic repair
          fix: true}}, {// The following loader will only match one
        // Note: no two configurations can handle the same type of file, so esLint is extracted
        oneOf: [
          // Loader configuration details
          {
            // Match those files
            test: /\.css$/.// Use those loader processes
            use: [
              ...commonCssLoader
            ]
          },
          {
            test: /\.less$/,
            use: [
              ...commonCssLoader,
              'less-loader']},...Copy the code

18. The cache

CacheDirectory: true, 2 cacheDirectory: true, 2 File resource cache Hash: A new unique hash value is generated each time a Webpack is built. Chunkhash: The hash value generated by chunk. If the package comes from the same chunk, the hash value will be the same. Question: Js and CSS hash values are still the same because CSS was introduced in JS and belongs to the same chunk contenthash: The hash value is generated based on the content of the file


  / / output
  output: {
    // Output the file name
    filename: 'js/built.[contenthash:10].js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},Copy the code

19.tree shaking

/* tree shaking: Remove useless code prerequisite: 1. Must use ES6 modularity 2. Enable production environment mode without modifying other! Json: "sideEffects":false all code has no sideEffects (tree shaking) SideEffects :["*.css"] CSS does not need to be tree shaking */
Copy the code

20. Production environments optimize code segmentation and load on demand

    1. Modify entry [Later can distinguish single page program (SPA) or multi-page program (MPA)]
  / / a single entrance
  // entry: './src/js/index.js',
  // Multiple entry, generate multiple package files
  entry: {
    main: './src/js/index.js'.test: './src/js/test.js'
  },
Copy the code
    1. Optimization methods
module.exports = {
  / / a single entrance
  entry: './src/js/index.js'./ / output
  output: {
    // Output the file name
    filename: 'js/[name]_built.[contenthash:10].js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'build')},// The node_modules code can be packaged separately as a chunk output
  // Automatically analyzes whether there are public dependent files in the multi-entry chunk. If so, it is packaged into a separate chunk. Don't pack more than once
  optimization: {
    splitChunks: {
      chunks: 'all'}},...Copy the code
    1. Js code method
/* Through the js code. Let a file be packaged separately as a chunk import for ES10 syntax webpackChunkName:'test' to name the packaged chunk */

import(/* webpackChunkName:'test' */ './test')
  .then(({ add }) = > {
    console.log(add(1.2.3));
  })
  .catch(() = > {
    console.log('File loading is failed... ');
  });
Copy the code

21. A lazy loading

// Lazy loading: files are loaded only when needed
// Prefetch: prefetch is loaded before use. Wait for other resources to load, the browser is free and then secretly load in the background
import(/* webpackChunkName:'test' ,webpackPrefetch:true*/ './test').then(
  ({ add }) = > {
    console.log('test 'is loaded... ');
    add(2.3); });Copy the code

22. PWA

  • PWA: Progressive Web development applications
  • Plug-in: workbox – webpack – the plugin
// WebPack plugin configuration
const workboxWebpackPlugin = require('workbox-webpack-plugin');
// Generate a Serviceworker profile. The default is at the root of the package
new workboxWebpackPlugin.GenerateSW({
  clientsClaim: true /* Help ServiceWorker start quickly */.skipWaiting: true /* Delete the old serviceworker */
});
Copy the code
// Register the Serviceworker in the entry file
if ('serviceWorker' in navigator) {
  window.addEventListener('load'.() = > {
    navigator.serviceWorker
      .register('./service-worker.js')
      .then(() = > {
        console.log('Sw registered successfully');
      })
      .catch(() = > {
        console.log('SW registration failed');
      });
  });
} else {
  console.log('error');
}
Copy the code

23. Multiple processes

  • Thread-loader needs to be installed, usually only after Babel (it must be executed later)
{

  test: /\.js$/,
  exclude: /node_modules/,
  use: [
    /* Enable multi-process packaging It takes time to start a process and time to communicate with a process
  {
    loader:'thread-loader'.options: {workers:2 // Process two}}, {loader: 'babel-loader'.options: {
      presets: [['@babel/preset-env',
          {
            // Load as needed
            useBuiltIns: 'usage'.// Specify the version of core-js
            corejs: {
              version: 3
            },
            // Specify which browser version is compatible with
            targets: {
              chrome: '60'.firefox: '60'.ie: '9'}}]]}],}}Copy the code

24.externals

  mode: 'production'./* Production mode */
  externals: {
    // Refuse jQuery to be packaged and introduced into HTML templates via CDN
    jquery: 'jquery'
  }
Copy the code

25.DLL

  • Create a new file, webpack.dll. Js, with the following content
/* Use DLL technology to package some libraries (vue, jquery, etc.) separately. Change the command to run: webpack --config webpack.dll. Js, change the configuration file to run to find */
const { resolve } = require('path');
const webpack = require('webpack');
module.exports = {
  / / the entry
  entry: {
    // [name]-- jQuery
    // ['jquery'] the name of the library to be packaged jquery
    jquery: ['jquery']},/ / output
  output: {
    // Output the file name
    filename: '[name].js'.// Output path
    // __dirname nodejs variable. Represents the path to the directory of the current file
    path: resolve(__dirname, 'dll'),
    library: '[name]_[hash]' // What is the name of the library exposed after packaging
  },

  plugins: [
    // Package to generate the manifest.json file. --> Provide mapping with jquery
    new webpack.DllPlugin({
      name: '[name]_[hash]'.// The exposed content name of the mapping library
      path: resolve(__dirname, 'dll/manifest.json') // Output mapping file})].mode: 'production' /* Production mode */
};
Copy the code
  • Webpack. Config. Js
const { resolve } = require('path');
const webpack = require('webpack')
const addAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin')
module.exports = {
...
  plugins: [
    // Tell WebPack which libraries do not participate in packaging and that their names need to be changed to reconfigured packaging
    new webpack.DllReferencePlugin({
      manifest:resolve(__dirname,'dll/manifest.json')}),// Package a file and import the resource in HTML
    new addAssetHtmlWebpackPlugin({
      filepath: resolve(__dirname, 'dll/jquery.js')})],mode: 'production'./* Production mode */
}
Copy the code

4. Detailed configuration:

26.entry

const { resolve } = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');

/* 1. string >> entry: './ SRC /index.js', which is packaged into a chunk and outputs a bundle file */
module.exports = {
  entry: './src/index.js'.output: {
    filename: '[name].js'.path: resolve(__dirname, 'build')},plugins: [new htmlWebpackPlugin()],
  mode: 'development'
};

/* 2. Array >> ['./ SRC /index.js','./ SRC /add.js'] multiple entries are packaged into a chunk and output a bundle
module.exports = {
  entry: ['./src/index.js'.'./src/add.js'].output: {
    filename: '[name].js'.path: resolve(__dirname, 'build')},plugins: [new htmlWebpackPlugin()],
  mode: 'development'
};

/* 3. object >> { index: './src/index.js', add: './ SRC /add.js'} Multiple entries are packaged to form multiple chunks, and multiple bundle names are output as key special usage: {// index does not introduce add. It will also be packaged in chunk of index. Index: ['. / SRC/index. Js', '. / SRC/add. Js'], / / the first case the add: 'the. / SRC/add. Js'} * /
module.exports = {
  entry: { index: './src/index.js'.add: './src/add.js' },
  output: {
    filename: '[name].js'.path: resolve(__dirname, 'build')},plugins: [new htmlWebpackPlugin()],
  mode: 'development'
};
Copy the code

27.output

const { resolve } = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js'.output: {
    // File name (specify name + directory)
    filename: 'js/[name].js'.// Directory for output files (common directory for output of all resources)
    path: resolve(__dirname, 'build'),
    / / all the resources of the introduction of the common path - > 'imgs/a. pg = = > >'/imgs/a. pg '
    // publicPath: '/',
    // The name of the non-entry chunk
    chunkFilename: '[name]_chunk.js'.library: '[name]'.// The name of the variable exposed throughout the library
    libraryTarget: 'window' // Add the variable name to that object brower
    // libraryTarget:'global' // Add the variable name to that object node
  },
  plugins: [new htmlWebpackPlugin()],
  mode: 'development'
};
Copy the code

28.module

const { resolve } = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js'.output: {
    // File name (specify name + directory)
    filename: 'js/[name].js'.// Directory for output files (common directory for output of all resources)
    path: resolve(__dirname, 'build')},module: {
    rules: [
      // Load configuration
      {
        test: /\.css$/.// Multiple loaders use use
        use: ['style-loader'.'css-loader'] {},test: '/.js$/'.// Exclude third-party code
        exclude: /node_modules/.// Check only the code in the SRC directory
        include: resolve(__dirname, 'src'),
        // Use a single loader directly
        loader: 'eslint-loader'.// Priority execution
        enforce: 'pre'
        /* // Enforce :'post' */
      },
      {
        // Only one loader will take effect
        oneOf: []}]},plugins: [new htmlWebpackPlugin()],
  mode: 'development'
};
Copy the code

30.resolve

const { resolve } = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js'.output: {
    // File name (specify name + directory)
    filename: 'js/[name].js'.// Directory for output files (common directory for output of all resources)
    path: resolve(__dirname, 'build')},// Parse the module's rules
  resolve: {
    // Configure the path alias
    alias: {
      The '@': resolve(__dirname, 'src')},// Omit the file path suffix
    extensions: ['js'.'vue'].// Tells Webpack which directory to go to
    modules: ['node_modules']},plugins: [new htmlWebpackPlugin()],
  mode: 'development'
};
Copy the code

31.devServer

/* Webpack.config. js Webpack's config file is used to tell webpack what to do. All the components of the tool run on the NodeJS platform, modularity default commonJS */

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  / / the entry
  entry: './src/index.js'.devServer: {
    // Directory to run the code
    contentBase: resolve(__dirname, 'build'),
    // Monitor file changes, reload
    watchContentBase: true.// Do not monitor third-party code
    watchOption: {
      ignored: /node_modules/
    },
    // Start gzip compression
    compress: true./ / the port number
    port: 3000.// Automatically open the browser
    open: true./ / domain name
    host: 'localhost'./ / open HMR
    hot: true.// Logs about starting the server are not displayed
    clientLogLevel: 'none'.// No content is displayed except basic information
    quiet: true.// If an error occurs, do not display it in full screen
    overlay: false.// Server proxy -- addresses cross-domain issues in development environments
    proxy: {
      // Once devServer receives the/API /XXX request, it forwards the request to the target server (target:'http://www.douban.com')
      '/api': {
        target: 'http://www.douban.com'.// Path rewrite, will/API /XXX request ==== "" /XXX request
        pathRewrite: {
          '^/api': ' '}}}}};Copy the code