Foreword – Read the webpack book in practice

directory

  • Entry: The first step in Webpack’s execution of the build starts with an Entry, which can be abstracted into input.
  • Output: export, input result.
  • Webpack will recursively find all dependent modules from the configured Entry.
  • Resolve: How is the module resolved
  • Externals: Optimizes performance without packaging some dependent modules
  • Devserver: Hot update, configure service IP, port, etc

The core concept

Webpack starts by recursively resolving all modules that an Entry depends on, starting from the Module configured in the Entry. Every time a Module is found, the system finds the corresponding conversion rule according to the configured Loader, converts the Module, and resolves the Module that the current Module depends on. These modules are grouped into entries. An Entry and all its dependent modules are grouped into a Chunk and Webpack will then convert all chunks into a file output.

Entry

You can configure a multi-page application or a single-page application with multiple entries. The following configuration methods are as follows: Entry: Can be dynamically configured to accept a function or a promise

module.exports  = {
  entry: './main.js'   / / type string
};
module.exports  = {
  entry: ['./main.js'.'./main2.js']   
  // The module of the last entry file in the array will be exported.
};
module.exports  = {
  entry: { 
      demo1:  './entry/demo1.js'.demo2:  './entry/demo2.js'./ / the object type}};Copy the code

Output

Configure the egress where the commonly used properties are configured, we commonly use filename, path, publicPath

Filename: the name of the exported file is a string. To export a single file, you can write a fixed string filename: “./main.js”. To export multiple files, you must use a built-in variable. “[name].js”, where [name] refers to the built-in variable name, webpack will give each chunk a built-in name.

Path: the path module of node is used to obtain the absolute path __dirname, followed by a string, which is the exit file directory configuration

PublicPath: indicates the path prefix of the static resource referenced after the package. For example, publicPath: a/b. The path of the static resource referenced after the package is http://www.XXX.com/a/b/

/ / sample
module.exports = {
	output: {
	    filename: "".// Export file nicknames, which can be used dynamically using the built-in variable name
	    chunkFilename: "".// The string needs to be generated in Runtime based on the chunk request
	    path: path.resolve(__dirname, 'dist'), // Generate the export file directory,__dirname is the root
            publicPath: "".// The path of the static resource. The configuration needs to be based on the development or production environmentThe library:"".// string The name of the exported library
	    libraryTarget: "".// How to export the library
	    libraryExport: "".// String, array exports those submodules}}Copy the code

Built-in variables Note: The length of the Hash can be specified. For example, [Hash :8]. The default value is 20.

Module

Webpack will recursively find all dependent modules from the configured Entry. This is equivalent to configuring rules for handling modules. Use noParse, rules

NoParse: Improves WebPack performance by ignoring parsing and processing of certain files (omitted files should not include import, require, define). For example, jquery is not modularized, so parsing and processing are not required.

In this section, we simply introduce the basic configuration of Test and use of Loader, and we extend some of the following items, such as: Enforce, include, exclude.

module.exports  = {
	module: {
	    parser: {  // Specifies the parser switch, which controls exactly what syntax can be parsed
	       amd: false./ / disable AMD
	       commonjs: true./ / disable CommonJs. },noParse: /jquery/ ,  // Ignore partial parsing and processing of files (omitted files should not contain import, require, define)
	    rules: [  // Configure Loader, which we shared in Section 1
	      {
	        test: /\.css/.// The matching rule of the regular expression can also be an array
	        use: [],  // Array can be string, object
	        enforce: "pre".// enum ["pre", "post"] Sets the execution sequence of LOder
	        // Post puts the loader execution order last
	        // Pre puts the loader execution order first
	        
	        include: path.resolve(__dirname, 'src'), // Only matches files in the SRC directory and accepts arrays
	        exclude: path.resolve(__dirname, 'dist'), // Exclude files from the dist directory and accept an array. Here's an example:
	        // include: [path.resolve(__dirname, 'src'),path.resolve(__dirname, 'src2')]}}}]Copy the code

Resolve

How modules are parsed, (Webpack itself has default values), commonly used alias, Extensions

Alias: Create aliases to avoid too many relative paths. In development we will definitely reference static directories for various levels of components.. This is a reference alias configuration. Convenient development, improve efficiency.

Extensions: Reference file or component. Import a from “a” by default. If there is no extension, you will find a.js, a.JAXon. Extensions: [“.js”,”.json”]. Therefore, it is recommended that reference files or components be named with a suffix to avoid unnecessary parsing.

module.exports = {
	resolve: {
	   alias: { // Create an alias. Make references more convenient and avoid excessive relative paths
	      images: path.resolve(__dirname, 'src/images/') 
	      css$: path.resolve(__dirname, 'src/assets/css')  // The $identifier matches exactly
	    },
	    extensions: [".js".".json"].// If there is no suffix, suffix resolution is automatically applied by default
	    mainFiles: [].// Specify which part of the code to import when importing the module
	    modules: ["node_modules"].// By default, only third-party modules are found in node_modules
	    enforceExtension: false.// Allow references to files with no extension
	    unsafeCache: /\aa/.Regex, array, Boolean
	    plugins: [],  // A list of additional parse plug-ins}}Copy the code

Externals

The package size is too large to package some plug-in source modules into a file.

module.exports = {
	externals: {
	    jquery: 'jQuery'  // string, array. object, function, regex}}Copy the code

Devserver

Commonly used host, port, open, proxy, this configuration is quite a lot, later we will have a basic combat share, please continue to pay attention to. website

module.exports = {
	devServer: {
	   host: "".// The default value is localhost. Set the IP address for external access
	   port: "".// The default listening port is 8080
	   inline: true.If false, the iframe mode is enabled. If true, the iframe mode is embedded in the bundle
	   allowedHosts: [].// Set the whitelist
	   compress: true.// Enable gzip compression
	   contentBase: path.join(__dirname, "public"), // Where to extract the static file from, default to the current execution directory./
	   disableHostCheck: false.// Disable host check to enable other devices to access local services
	   lazy: true.// Enable lazy mode, compiling only on request, that is, not listening for file changes
	   filename: "".// Compile only when the file is requested. Lazy mode must be enabled
	   headers: {},  // Add header content to all desired uses
	   hot: true.// Enable hot replacement of modules and refresh only the changed modules
	   clientLogLevel: "info".// enum Log level of the client. The default value is INFO
	   https: true.By default, HTTP is used. After HTTPS is enabled, a certificate is automatically generated. You can also configure your own certificate and read files by using {}
	   open: true.// Open the browser automatically after the first build
	   proxy: { / / agent
	     "/api":  "http://localhost:3000"."/users": {
	       target: "https://localhost:3000".pathRewrite: {"^/users" : ""},  // Rewrite the path as /users/login -> /login
	       secure: false.// If the proxy is to the HTTPS service, set secure to false
	       bypass: function(req, res, proxyOptions) {
	         if (req.headers.accept.indexOf("html")! = = -1) {
	           console.log("Skipping proxy for browser request.");
	           return "/index.html"; }}}},quiet:  true.// Nothing is printed to the console except the initial startup information}}Copy the code

Up to here, webPack part of the property configuration, have a simple introduction and understanding, I will practice a version of WebPack performance optimization actual fight

Welcome to like, a little encouragement, a lot of growth

A link to the

  • Front-end visualization platform implementation scheme
  • Getting started with WebPack is a must
  • Webpack advanced with core