What kinds of webpack plug-ins do you use?

background

Recently, I've been looking at something related to weback plug-ins. I don't know a lot about weback, but these things are necessary for senior programmers to master. Try to learn.

introduce

Official website: https://www.webbackjs.com/concepts/plugins/
There are so many things on the official website:

Official website content

 

  • Concept: it's a packer, which packs what we write into something that can be recognized by the browser, and simplifies, compresses and so on;

  • entry: specify a file path, and web pack will start from here (package, compile, compress, etc.);

  • Output: when the webpack is finished, it will be output to the specified location;

  • Loader: loader is used to convert the source code of the module. Because webpack itself can only package the js file of commonjs specification, which can be understood as code processing. For example, how to finally process less into css requires loader to process.

  • plugins: understand the extensions of paired projects and webacks. For example, in development, hot replacement (also available below) is plug-ins. For example, dllpulgin (to speed up packaging, separate packaging) and so on. Used to assist development and extend the function of webpack.

  • Configuration: the configuration content of the webpack.js file, which functions can be configured

  • Modules: the modules that webback can support are ts, sass, less, coffeespcript, ESNext.

  • manifest: when the web pack is packaged, our src and other paths do not exist, so how to find the path? It is to find the corresponding path and dependency through mainfest.json file.

  • Build target: the language used to specify the environment in which the web pack is built, such as:

 

module.exports = {
  target: 'node'
};

Using node webback will be compiled for the "node like. JS" environment. If you need to know which target s are supported, please refer to the following link:
https://www.webpackjs.com/configuration/target/

  • HMR - hot module replacement: it is a real-time compilation function in development. Locally written code does not need to be refreshed manually, and the page will be refreshed automatically by saving.

Common plug-ins

DefinePlugin: a global constant that allows configuration at compile time

Usage:

webpack.config.js file (all plug-ins need to be created in new mode):

 

//Establish:
 new webpack.DefinePlugin({
            "test":{a:1}
}),

app.js :

 

//Use:
console.log(test);//It can be used directly without introduction

DllPlugin: to greatly reduce the construction time, separate and package

DLLPlugin and DLLReferencePlugin realize the splitting of bundles in some way, and at the same time greatly improve the construction speed.

The plug-in is to create a dll only bundle in an extra independent web pack setting. This plug-in will generate a file named manifest.json, which is used to map DLLReferencePlugin to related dependencies.

In the following example, we pack our commonly used jquery and lodash, and the two libraries will not change frequently. We pack them separately. In the future, we don't need to pack the files of these two static resources. We only pack the files under our src, so as to speed up the packing.

webpack.dll.js

 

const webpack=require('webpack');
module.exports = {
    entry:{
        vendor:['jquery','loadsh']
    },
    output:{
        path:__dirname+"/dll",
        filename:"[name].js",
        library:"[name]_library"
    },
    plugins:[
        new webpack.DllPlugin({
            path:__dirname+"/dll/[name]-mainfest.json",
            name:"[name]_library",
            context:__dirname
        })
    ]
}

Compiling the above code will generate the following files in the directory:

 

dll directory

webpack.config.js

 

const webpack=require('webpack');
module.exports = {
    entry:{
        app:'./app.js'
    },
    output:{
        filename:"[name].js"
    },
    plugins:[
        new webpack.DefinePlugin({
            "test":{a:1}
        }),
        new webpack.DllReferencePlugin({
            context: __dirname,
            manifest: require("./dll//vendor-mainfest.json"),
            // name: "./my-dll.js",
            // scope: "xyz",
            // sourceType: "commonjs2"
          })
        // new webpack.ProvidePlugin({
        //     $:'jquery'
        // })
    ]
}

vendor-mainfes

 

In the vendor mainfes file is a string of json, which are the addresses of some paths.

EnvironmentPlugin: shorthand for the process.env key in DefinePlugin.

EnvironmentPlugin is a shortcut to set the process.env environment variable through DefinePlugin.

 

new webpack.EnvironmentPlugin(['NODE_ENV', 'DEBUG'])

Equivalent to

 

new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  'process.env.DEBUG': JSON.stringify(process.env.DEBUG)
})

Extract text web pack plugin: extract text (CSS) from bundle s to separate files

install

 

npm install --save-dev extract-text-webpack-plugin
# For webpack 2
npm install --save-dev extract-text-webpack-plugin@2.1.2
# For webpack 1
npm install --save-dev extract-text-webpack-plugin@1.0.1

Usage:

 

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

HotModuleReplacementPlugin: enable hot module replacement - HMR

 

new webpack.HotModuleReplacementPlugin({
  // Options...
})//Just add this sentence

HTML webpackplugin: simple creation of HTML files for server access

Need to install

 

npm install --save-dev html-webpack-plugin

The plug-in will generate an HTML5 file for you, including all the webpacks in the body using the script tag. Just add plug-ins to your webpack configuration as follows:

 

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

var webpackConfig = {
  entry: 'index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]//Add here
};

This will produce a file dist/index.html with the following contents:

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>webpack App</title>
  </head>
  <body>
    <script src="index_bundle.js"></script>
  </body>
</html>

ProvidePlugin: no need to use modules through import/require

Automatically load modules without having to import or require them everywhere.

webpack.config.js

 

new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery'
})
or
new webpack.ProvidePlugin({
  identifier: ['module1', 'property1'],
  // ...
})

Then in our arbitrary source code:

 

// in a module
$('#Item '); / / < works
jQuery('#Item '); / / < works
// $is automatically set to "jquery" output

 

Published 21 original articles, won praise 5, 20000 visitors+
Private letter follow

Keywords: Webpack JQuery JSON npm

Added by skalar on Sun, 15 Mar 2020 11:03:26 +0200